c++ - 从重载函数中提取返回类型

标签 c++ templates return-value overloading c++11

我想提取函数的返回类型。问题是,还有其他同名但签名不同的函数,我无法让 C++ 选择合适的函数。我知道 std::result_of,但通过几次尝试我得出结论,它也遇到了同样的问题。我也听说过涉及 decltype 的解决方案,但我不知 Prop 体细节。

目前我正在使用模板元编程从函数指针类型中提取返回类型,这适用于有限数量的参数(任何非限制解决方案?),因为函数指针类型的提取适用于明确的功能。

#include <iostream>

using namespace std;

//  ----

#define resultof(x)     typename ResultOf<typeof(x)>::Type  //  might need a & before x

template <class T>
class ResultOf
{
    public:
        typedef void Type;      //  might need to be T instead of void; see below
};

template <class R>
class ResultOf<R (*) ()>
{
    public:
        typedef R Type;
};

template <class R, class P>
class ResultOf<R (*) (P)>
{
    public:
        typedef R Type;
};

//  ----

class NoDefaultConstructor
{
    public:
        NoDefaultConstructor (int) {}
};


int f ();
int f ()
{
    cout << "f" << endl;
    return 1;
}

double f (int x);
double f (int x)
{
    cout << "f(int)" << endl;
    return x + 2.0;
}

bool f (NoDefaultConstructor);
bool f (NoDefaultConstructor)
{
    cout << "f(const NoDefaultConstructor)" << endl;
    return false;
}

int g ();
int g ()
{
    cout << "g" << endl;
    return 4;
}

int main (int argc, char* argv[])
{
    if(argc||argv){}

//  this works since there is no ambiguity. does not work without &
//  resultof(&g) x0 = 1;
//  cout << x0 << endl;

//  does not work since type of f is unknown due to ambiguity. same thing without &
//  resultof(&f) x1 = 1;
//  cout << x1 << endl;

//  does not work since typeof(f()) is int, not a member function pointer; we COULD use T instead of void in the unspecialized class template to make it work. same thing with &
//  resultof(f()) x2 = 1;
//  cout << x2 << endl;

//  does not work per above, and compiler thinks differently from a human about f(int); no idea how to make it correct
//  resultof(f(int)) x3 = 1;
//  cout << x3 << endl;

//  does not work per case 2
//  resultof(f(int())) x4 = 1;
//  cout << x4 << endl;

//  does not work per case 2, and due to the lack of a default constructor
//  resultof(f(NoDefaultConstructor())) x5 = 1;
//  cout << x5 << endl;

//  this works but it does not solve the problem, we need to extract return type from a particular function, not a function type
//  resultof(int(*)(int)) x6 = 1;
//  cout << x6 << endl;

}

知道我缺少什么语法功能以及如何修复它,最好使用一种以简单方式工作的解决方案,例如resultof(f(int))?

最佳答案

我认为这可以通过 decltype 来完成和 declval :

例如:decltype(f(std::declval<T>())) .

关于c++ - 从重载函数中提取返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7260561/

相关文章:

C++ 使用类 A 作为类 B 的成员函数的参数,类 B 是类 A 的成员

c++ - 在 C++ 中实现枚举类型

c++ - 函数模板特化类型——它是可选的吗?

c++ - 列表初始化器和可变参数构造函数

c++ - OpenCV VideoCapture 在 Open 或 Constructor 上超时?

java - Java 中是否有像 C++ 那样的成员初始化列表语法?

c++ - 编译时间与运行时递归

c++ - 具有按值返回和 noexcept 的函数

mysql - 为什么 MySQL SLEEP() 函数返回 0?

c++ - 在不破坏 C++ 抽象的情况下处理对存储在私有(private)映射中的值的封装访问的标准方法