Click here to Skip to main content
15,885,030 members
Articles / Programming Languages / C++
Tip/Trick

How to Let the Compiler Declare the Type of a Variable for Later Initialization by a Function

Rate me:
Please Sign up or sign in to vote.
3.00/5 (2 votes)
4 May 2020CPOL1 min read 7K   30   1   11
This tip demonstrates the use of the STL template std::invoke_result
The template std::invoke_result defined in when used with decltype allows the compiler to deduce the type of a function return via its name any template parameters and the types of its arguments. This is useful when needing to declare a variable which will be initialized later in the file by a particular function.

The template std::invoke_result (since C++17) defined in <type_traits> when used with decltype allows the compiler to deduce the return type of a function or method via its name its class name template parameters and the types of its arguments. This is useful when needing to declare a variable which will be initialized later in the file by a particular function or method.

You of course know about and utilize auto to declare the type of a variable when also initializing it with a function or method call. However if you happen to need to declare such a variable without first such initialization the template std::invoke_result (since C++17) defined in <type_traits> is helpful. When used with decltype it permits declaring the type of a variable based on the name of a particular function or method via its name its class name template parameters and types of its arguments so no need to concern yourself with precise knowledge of the return type. Omitting the legal details for functions it is used as

using return_type = std::invoke_result<decltype(templated function name), type of arg1, etc.>::type;

For methods it is used as

using return_type = std::invoke_result<decltype(&templated class name::templated function name), templated class name, type of arg1, etc.>::type;

The code below demonstrates this with five examples of increasing complexity. The first example demonstrates its use for a function with no arguments. The fourth example demonstrates that if the return type does not depend on a template parameter then it does not matter that the function template parameter utilized within decltype is not the same as that utilized when actually calling the function. The last example demonstrates its use for a method.

#include <iostream>
#include <vector>
#include <type_traits>

using namespace std;

template<class T>
class cfoobar
{
public:
	double foobar(int) { return 0.; }
};

int foobar() { return 0; }
using foobar_return_type = invoke_result<decltype(foobar)>::type;

int goobar(int&, double*) { return 0; }
using goobar_return_type = invoke_result<decltype(goobar), int&, double*>::type;

template<class T>
T hoobar(T) { return T(); }
using hoobar_return_type = invoke_result<decltype(hoobar<cfoobar<int>>), cfoobar<int>>::type;

template<class T>
vector<int> koobar(T, double) { return vector<int>(); }
using koobar_return_type = invoke_result<decltype(koobar<cfoobar<int>>), cfoobar<int>, double>::type;

using cfoobar_foobar_return_type = invoke_result<decltype(&cfoobar<int>::foobar), cfoobar<int>, int>::type;

int main()
{
	cout << typeid(foobar_return_type).name() << endl;
	cout << typeid(goobar_return_type).name() << endl;
	cout << typeid(hoobar_return_type).name() << endl;
	cout << typeid(koobar_return_type).name() << endl;
	cout << typeid(cfoobar_foobar_return_type).name() << endl;
}

The output shown below demonstrates its correctness.

int
int
class cfoobar<int>
class std::vector<int,class std::allocator<int> >
double

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
MS Physics Drake University
BA Mathematics Dominican University
Wrote world's first user configurable binary file editor utilizing templates to specify file structure id est to wit in particular to be specific "FileRay" unfortunately not a commercial success. Some years later Sweetscape did a better job w/ "010 Editor" and seems to be a success.
Enjoy physical simulation. Did some work in this regard in astro-physics and options market making.

Home Page
https://mypaltrythoughts.blogspot.com/

Below is my "Signature" apologies for no apologies if offends
My sympathies to the SPAM moderator
"I once put instant coffee into the microwave and went back in time." - Steven Wright
"Shut up and calculate" - apparently N. David Mermin possibly Richard Feynman
“I want to sing, I want to cry, I want to laugh. Everything together. And jump and dance. The day has arrived — yippee!” - Desmond Tutu
“When the green flag drops the bullshit stops!”
"It is cheaper to save the world than it is to ruin it."
"I must have had lessons" - Reverend Jim Ignatowski / Christopher Lloyd
"Dripping water hollows out stone, not through force, but through persistence." - Ovid, Roman poet
"... as likely as lightning striking a leprechaun whilst riding a unicorn."
"Don't worry, the planet will do just fine without us."
"We can't solve today's problems with the mentality that created them." Albert Einstein
“Much becomes obvious in ­hindsight, ... Yet it is striking how in both physics and mathematics there is a lack of ­proportion between the effort needed to understand something for the first time and the simplicity and naturalness of the solution once all the required stages have been completed.” - Giorgio Parisi, recipient of the 2021 Nobel Prize in Physics
"The only place where Success comes before Work is in the dictionary." Vidal Sassoon, 1928 - 2012
"Insanity in individuals is rare, but in groups, parties, nations, it is the rule." - Nietzsche

Comments and Discussions

 
Questionmy solution Pin
Member 105233475-May-20 0:21
Member 105233475-May-20 0:21 
AnswerRe: my solution Pin
BernardIE531712-May-20 4:14
BernardIE531712-May-20 4:14 
GeneralRe: my solution Pin
Member 1052334712-May-20 5:55
Member 1052334712-May-20 5:55 
GeneralRe: my solution Pin
BernardIE531712-May-20 8:04
BernardIE531712-May-20 8:04 
GeneralRe: my solution Pin
Member 1052334712-May-20 8:48
Member 1052334712-May-20 8:48 
GeneralRe: my solution Pin
BernardIE53175-Aug-20 19:28
BernardIE53175-Aug-20 19:28 
GeneralRe: my solution Pin
Member 105233475-Aug-20 21:18
Member 105233475-Aug-20 21:18 
GeneralRe: my solution Pin
BernardIE53176-Aug-20 9:37
BernardIE53176-Aug-20 9:37 
GeneralRe: my solution Pin
Member 105233477-Aug-20 0:03
Member 105233477-Aug-20 0:03 
GeneralRe: my solution Pin
Member 105233477-Aug-20 4:28
Member 105233477-Aug-20 4:28 
GeneralRe: my solution Pin
BernardIE53177-Aug-20 8:35
BernardIE53177-Aug-20 8:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.