【问题标题】:Is function object returned by std::mem_fn required to have a const overloadstd::mem_fn 返回的函数对象是否需要具有 const 重载
【发布时间】:2015-04-16 04:24:39
【问题描述】:

当我用 libc++ 运行这段代码时:

struct foo
{
    foo(int x) : x(x)
    {}
    int x;
};

int main()
{
    const auto select_x = std::mem_fn(&foo::x);
    foo f(1);
    printf("%i\n", select_x(f));
}

我收到这样的错误:

mem_fn.cpp:16:20: error: no matching function for call to object of type
      'const std::__1::__mem_fn<int foo::*>'
    printf("%i\n", select_x(f));
                   ^~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/functional:1224:11: note: 
      candidate function not viable: 'this' argument has type 'const
      std::__1::__mem_fn<int foo::*>', but method is not marked const
          operator() (_ArgTypes&&... __args)
          ^

似乎 libc++ 缺少const 重载。它使用 libstdc++ 工作。这是 libc++ 中的错误吗?或者标准是否需要const 重载?

【问题讨论】:

    标签: c++ c++11 clang libc++


    【解决方案1】:

    我没有看到有关mem_fn 返回的包装器的 const 可调用性的标准指定任何内容。来自 [func.memfn](引用 N4140):

    template<class R, class T> unspecified mem_fn(R T::* pm);
    

    1 返回:一个简单的调用包装器 (20.9.1) fn,这样 表达式fn(t, a2, ..., aN) 等价于INVOKE (pm, t, a2, ..., aN) (20.9.2)。 fn 应该有一个嵌套类型 result_typepm 是指向的指针时,是pm 的返回类型的同义词 成员函数。

    2 简单调用包装器应定义两个嵌套类型,命名为 argument_type 和 result_type 作为cv T*Ret 的同义词, 分别,当 pm 是指向成员函数的指针时 cv-qualifier cv 并且不带参数,其中 Retpm 的 返回类型。

    3 简单的调用包装器应定义三种嵌套类型 命名为 first_argument_typesecond_argument_typeresult_type 分别是 cv T*T1Ret 的同义词, 当pm 是指向具有cv-qualifier cv 的成员函数的指针和 取一个T1 类型的参数,其中Retpm 的返回类型。

    4 投掷:什么都没有。

    对 [func.def] 的引用(尽管 简单的调用包装器实际上是在 [func.require] 中定义的)同样没有意义。这几乎只能保证它返回的任何东西都可以直接使用。

    不过,作为一个实施质量问题,我看不出为什么包装器不应该是 const 可调用的,而且看起来这个问题实际上已经修复 over a year ago。您可能想尝试更新您的 XCode,看看是否可以选择更新版本的库。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-08
      • 1970-01-01
      • 2021-07-18
      • 2016-11-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多