我想提取函数的返回类型。问题是,有其他具有相同名称但不同签名的函数,我无法让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;
}
你知道我缺少哪些语法特性以及如何修复它吗?最好能提供一种简单的解决方案,例如resultof(f(int))
?
String operator + (const String& obj)
操作符,我希望ref<String>也有一个String operator + (const String& obj)
操作符。参数(有限的数量)的推导已经解决了,因为它是一个简单的模板,但返回类型的推导是有问题的。 - Frigostd::ref
已经实现了这个功能。它提供了一个操作符(Args...),可以正确地传递函数(或函数对象)的引用。它还具有隐式转换为T类型的引用。如果你没有使用C++11,我建议看一下boost::result_of的使用方法,了解它的工作原理。 - Dave Sboost::type_traits
和boost::remove_pointer
吗? http://www.boost.org/doc/libs/1_47_0/libs/type_traits/doc/html/boost_typetraits/reference/function_traits.html - Tom Kerr