Fri*_*igo 11 c++ templates overloading return-value c++11
我想提取函数的返回类型.问题是,还有其他函数具有相同的名称但签名不同,我无法让C++选择合适的函数.我知道std :: result_of,但是从几次尝试我得出结论它也遇到了同样的问题.我也听说过涉及decltype的解决方案,但我不知道具体细节.
目前我正在使用模板元编程从函数指针类型中提取返回类型,这对于有限数量的参数(任何非限制解决方案?)都可以正常工作,因为函数指针类型的提取适用于明确的函数.
#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;
}
Run Code Online (Sandbox Code Playgroud)
任何想法我缺少什么语法功能以及如何解决它,最好是一个简单的解决方案,例如resultof(f(int))
?
我认为这是可以做到的decltype
和declval
:
例如:decltype(f(std::declval<T>()))
.
归档时间: |
|
查看次数: |
1552 次 |
最近记录: |