English 中文(简体)
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?

问题回答

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.

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);
}

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:

  • This will work for functions of any arity up to 10, which should be enough for most sensible uses.
  • This use of BOOST_TYPEOF works on platforms that do not supply a native typeof, so it s reasonably portable.

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

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

As suggested by dribeas, here is the solution I eventually came to:

float Foo();
int Bar();

template<typename T> Monkey(T) {
    boost::function_traits< boost::remove_pointer<T>::type >::result_type var1 = ...;
    // Now do something
}

Monkey(Foo);
Monkey(Bar);

This isn t exactly the form I aimed for with my original question, but it s close enough for me.

Try something like this:

template<class T> struct magic_template
{};

template<class T> struct magic_template<T()>
{
    typedef T type;
};




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签