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

后端 未结 7 1718
温柔的废话
温柔的废话 2020-12-16 21:49

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         


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 22:51

    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 
    #include 
    
    float Foo();
    int Bar();
    
    int main()
    {
      boost::function_traits::result_type f = 5.0f;
      boost::function_traits::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.

提交回复
热议问题