【问题标题】:C++11 applies result_of on member function, failed, why?C++11对成员函数应用result_of,失败,为什么?
【发布时间】:2016-06-21 09:33:26
【问题描述】:

我有以下代码作为实验:

int f1() { return 0; }

struct Bar {
    Bar() = delete;
    int f() { return 0; }
    int operator()() { return 1; }
};

int main()
{
    decltype(f1()) x = 3;//f1() is expression
    result_of<decltype(&f1)()>::type x1 = 3;//type+param
    result_of<Bar()>::type x3 = 3;//type+param
    decltype(declval<Bar>().f()) y = 4;//expression
    decltype((((Bar*)nullptr)->*(&Bar::f))()) z = 5;//expression

    result_of<decltype(std::mem_fn(&Bar::f))()>::type y2 = 3;//error!!!!!!
}

除了最后一个result_of之外,一切正常: 我试图使用result_of 获取Bar::f 的返回类型。

为什么会失败,如何纠正?

【问题讨论】:

  • 它是一个成员函数,它需要一个隐式对象参数,即result_of&lt;decltype(std::mem_fn(&amp;Bar::f))(Bar)&gt;::type y2
  • 谢谢,它有效,但似乎“result_of::type y2 = 3;”也可以通过编译。哪个是正确的,为什么 BAR* 仍然可以给这个 mem_fn?
  • 使用指针或引用类型没有区别。这里重要的是价值类别和简历资格

标签: c++ c++11 types decltype result-of


【解决方案1】:

mem_fn未指定返回类型:

模板 未指定 mem_fn(R T::* pm) noexcept;

定义为INVOKE[func.memfn]/p1:

1返回:一个简单的调用包装器 ([func.def]) fn 使得表达式 fn(t, a2, ..., aN) 等价于 INVOKE(pm, t, a2, ..., aN) ([func.require]) .

INVOKE 的定义包括以下两个项目符号[func.require]/p1

定义<i>INVOKE</i>(f, t1, t2, ..., tN)如下:

——(t1.*f)(t2, ..., tN)f 是指向类T 的成员函数的指针并且is_base_of&lt;T, decay_t&lt;decltype(t1)&gt;&gt;::valuetrue 时;

——((*t1).*f)(t2, ..., tN)f是一个指向类T的成员函数的指针,而t1不满足前两项;

mem_fn返回的第一个参数必须是隐式对象参数(t1)的类型,可以是引用也可以是指针,例如:

std::result_of<decltype(std::mem_fn(&Bar::f))(Bar&)>::type y2;
//                                            ~~~^

std::result_of<decltype(std::mem_fn(&Bar::f))(Bar*)>::type y2;
//                                            ~~~^

您也可以完全删除 std::mem_fn

std::result_of<decltype(&Bar::f)(Bar*)>::type y2;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多