1

我需要获取类模板参数的成员函数的结果。不幸的是,我绑定到 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,因此我必须能够在编译时获得返回类型。

4

1 回答 1

1

std::tr1::result_of需要一个类型参数。您正在向它传递一个非类型(指向成员的指针)。

这使得std::tr1::result_of在没有decltype. 例如,您可以在包装函数中使用它:

template <typename Ct, typename Arg>
void some_wrapper(Ct fun, Arg arg)
{
    typedef typename std::tr1::result_of<Ct(Arg)>::type ret;
    ret result = fun(arg);
    // ... do something with result
}

但是您不能像尝试那样使用它。

于 2014-05-22T10:11:21.337 回答