Extracting the return type from an overloaded function

后端 未结 3 2067
臣服心动
臣服心动 2020-12-10 14:39

I want to extract the return type of a function. Problem is, there are other functions with the same name but different signature, and I can not get C++ to select the approp

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-10 15:19

    Okay, after a few attempts I managed to work around the std::declval method suggested by Mankarse. I used a variadic class template to fixate the parameters, and used the template deduction of functions to get the return value from a function pointer. Its current syntax is typeof(ResultOf::get(function)), unfortunately it is still far from the desired resultof(function) form. Will edit this answer if I find a way to further simplify it.

    #include 
    #include 
    
    using namespace std;
    
    template 
    class ResultOf
    {
        public:
            template 
            static R get (R (*) (Args...));
            template 
            static R get (R (C::*) (Args...));
    };
    
    class NoDefaultConstructor
    {
        public:
            NoDefaultConstructor (int) {}
    };
    
    int f ();
    double f (int x);
    bool f (NoDefaultConstructor);
    int f (int x, int y);
    
    
    int main (int argc, char* argv[])
    {
        if(argc||argv){}
    
        cout << typeid(typeof(ResultOf<>::get(f))).name() << endl;
        cout << typeid(typeof(ResultOf::get(f))).name() << endl;
        cout << typeid(typeof(ResultOf::get(f))).name() << endl;
        cout << typeid(typeof(ResultOf::get(f))).name() << endl;
    
        typeof(ResultOf::get(f)) d = 1.1;
        cout << d << endl;
    }
    

    Edit:

    Managed to solve it with variadic macros, the syntax is now resultof(f, param1, param2, etc). Without them I couldn't pass the commas between the parameter types to the template. Tried with the syntax resultof(f, (param1, param2, etc)) to no avail.

    #include 
    
    using namespace std;
    
    template 
    class Param
    {
        public:
            template 
            static R Func (R (*) (Args...));
            template 
            static R Func (R (C::*) (Args...));
    };
    
    #define resultof(f, ...) typeof(Param<__VA_ARGS__>::Func(f))
    
    int f ();
    double f (int x);
    int f (int x, int y);
    
    int main (int argc, char* argv[])
    {
        resultof(f, int) d = 1.1;
        cout << d << endl;
    }
    

提交回复
热议问题