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();
i
Try something like this:
template<class T> struct magic_template
{};
template<class T> struct magic_template<T()>
{
typedef T type;
};
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);
}
Here comes the template magic (no Boost
is involved):
template <typename ReturnType> class clFunc0
{
typedef ReturnType ( *FuncPtr )();
public:
typedef ReturnType Type;
};
template <typename ReturnType> inline clFunc0<ReturnType> ResultType( ReturnType ( *FuncPtr )() )
{
return clFunc0<ReturnType>();
}
#define FUNC_TYPE( func_name ) decltype( ResultType( &func_name ) )::Type
int test()
{
return 1;
}
int main()
{
FUNC_TYPE( test ) Value = 1;
return Value;
}
And compile it via
gcc Test.cpp -std=gnu++0x
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.
In C++ 0x, use decltype.
For a discussion on the problems and trying to construct a solution for an earlier C++ standard, see here:
Scott Myers "challenge" (PDF) and Andrei Alexandrescu trying to solve it
Foo and Bar are functions, not function types, so you need to do a bit of extra work.
Here's a solution using a combination of boost::function_traits and BOOST_TYPEOF.
#include <boost/typeof/typeof.hpp>
#include <boost/type_traits.hpp>
float Foo();
int Bar();
int main()
{
boost::function_traits<BOOST_TYPEOF(Foo)>::result_type f = 5.0f;
boost::function_traits<BOOST_TYPEOF(Bar)>::result_type i = 1;
return i;
}
Edit: