我需要获取类模板参数的成员函数的结果。不幸的是,我绑定到 C++03 并且不能使用 decltype,但是我可以使用 tr1::result_of。我尝试了以下代码,但这不适用于我的编译器(gcc 4.3,我也无法更改):
#include <tr1/functional>
struct ReturnType {};
struct O
{
ReturnType f();
};
template<typename T> struct A
{
typename std::tr1::result_of<(&T::f)(T*)>::type f();
};
void f()
{
A<O> a;
ReturnType x = a.f();
}
上面的代码反映了我的理解result_of<Fn(ArgTypes ...)
:
如果 Fn 是指向非静态成员函数的指针,并且 ArgTypes 中的第一个类型是该成员所属的类(或对它的引用,或对派生类型的引用,或指向它的指针),并且ArgTypes 中的其余类型描述了它的参数。
我将一个指向成员函数的指针传递给它,并将第一个参数类型指定为指向该类的指针。但是,编译器会打印以下错误:
result_of.cpp:12: error: `&' cannot appear in a constant-expression
result_of.cpp:12: error: a function call cannot appear in a constant-expression
result_of.cpp:12: error: template argument 1 is invalid
result_of.cpp:12: error: invalid use of ‘::’
result_of.cpp:12: error: expected ‘;’ before ‘f’
result_of.cpp: In function ‘void f()’:
result_of.cpp:18: error: ‘struct A<O>’ has no member named ‘f’
我无法将 O 类更改为例如添加结果 typedef,因此我必须能够在编译时获得返回类型。