c++ - std::mem_fn 返回的函数对象是否需要 const 重载

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

当我使用 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 重载?

最佳答案

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

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

1 Returns: A simple call wrapper (20.9.1) fn such that the expression fn(t, a2, ..., aN) is equivalent to INVOKE (pm, t, a2, ..., aN) (20.9.2). fn shall have a nested type result_type that is a synonym for the return type of pm when pm is a pointer to member function.

2 The simple call wrapper shall define two nested types named argument_type and result_type as synonyms for cv T* and Ret, respectively, when pm is a pointer to member function with cv-qualifier cv and taking no arguments, where Ret is pm’s return type.

3 The simple call wrapper shall define three nested types named first_argument_type, second_argument_type, and result_type as synonyms for cv T*, T1, and Ret, respectively, when pm is a pointer to member function with cv-qualifier cv and taking one argument of type T1, where Ret is pm’s return type.

4 Throws: Nothing.

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

不过,作为实现质量问题,我看不出为什么包装器不应该是常量可调用的,而且看起来这实际上已得到修复 over a year ago .您可能想尝试更新您的 XCode 以查看是否可以获取更新版本的库。

关于c++ - std::mem_fn 返回的函数对象是否需要 const 重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28528210/

相关文章:

c++ - 通过串行读取 utf8 时,Arduino 表现异常

c++ - boost 序列化 : Does the default constructor have to be public?

c++ - 如何实现枚举类对象的二维 vector ?

c++ - 有没有办法防止 vector 中的元素被破坏?

c - 我怎样才能让 clang 向量化一个简单的循环?

C++ 重构预编译头文件

c++ - 在 Raspberry Pi Jessie 上使用 OpenGL

c++ - 跨进程的 POSIX 共享内存同步 C++/C++11

c++ - Clang 前端 API 的所有权问题

c++ - 带有模板函数的 clang 编译错误