【问题标题】:result_of of call to member function of template parameter调用模板参数成员函数的result_of
【发布时间】:2014-05-22 09:02:55
【问题描述】:

我需要获取类的模板参数的成员函数的结果。不幸的是,我绑定到 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&lt;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 类更改为例如添加一个结果类型定义,所以我必须能够在编译时获得返回类型。

【问题讨论】:

    标签: c++ templates c++03 tr1 result-of


    【解决方案1】:

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

    这使得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
    }
    

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

    【讨论】:

    • 有没有什么方法可以在没有decltype的情况下获取成员函数的结果类型?从我引用的文档中,我希望成员函数指针有一个专门化,但这似乎是错误的。
    • 您可以传入成员函数指针type,但不能传入成员函数指针本身。这是一个基本的限制。您不能编写可以像mytemplate&lt;&amp;X::Y&gt; 与任何XY 一起使用的类模板。类模板必须知道其非类型参数的类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    相关资源
    最近更新 更多