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

后端 未结 7 1695
温柔的废话
温柔的废话 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:36

    Here comes the template magic (no Boost is involved):

    template  class clFunc0
    {
        typedef ReturnType ( *FuncPtr )();
    public:
        typedef ReturnType Type;
    };
    
    template  inline clFunc0 ResultType( ReturnType ( *FuncPtr )() )
    {
        return clFunc0();
    }
    
    #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
    

提交回复
热议问题