Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the return type of a function without calling it (using templates?)

I'm looking for a way in C++ to extract the return type of a function (without calling it). I presume this will require some template magic.

float Foo();
int Bar();

magic_template<Foo>::type var1; // Here 'var1' should be of type 'float'
magic_template<Bar>::type var2; // and 'var2' should be of type 'int'

I am currently investigating how magic_template might be implemented, but have not found a solution so far.

Any ideas?

like image 472
pauldoo Avatar asked Jan 05 '10 11:01

pauldoo


People also ask

Can we write a function without return type?

Function without return type stands for a void function. The void function may take multiple or zero parameters and returns nothing.

Why use trailing return type c++?

The trailing return type feature removes a C++ limitation where the return type of a function template cannot be generalized if the return type depends on the types of the function arguments.

Can return type be auto?

In C++14, you can just use auto as a return type.


2 Answers

Take a look at boost type traits library, in particular the function_traits template provides such functionality out of the box. If you cannot use boost, just download the code and read the sources for some insight into how it is done.

Note that the functionality is based on types, not concrete functions, so you might need to add some extra code there.


After doing some small tests, this might not be what you really need, and if it is the 'some extra code' will be non-trivial. The problem is that the function_traits template works on function signatures and not actual function pointers, so the problem has changed from 'get the return type from a function pointer' to 'get the signature from a function pointer' which is probably the hardest part there.

like image 50
David Rodríguez - dribeas Avatar answered Oct 21 '22 17:10

David Rodríguez - dribeas


It's tricky because function names are expression not types - you need something like gcc's typeof. Boost's TypeOf is a portable solution that gets very close.

However, if the code can be organised so that the work is done inside a function template to which Foo or Bar can be passed, there's a straight-forward answer:

template <class R>
void test(R (*)())
{
  R var1;
}

int main()
{
  test(&Foo);
}
like image 30
James Hopkin Avatar answered Oct 21 '22 16:10

James Hopkin