c++ - 编译器无法解析通过 std::mem_fn 传递的匹配类方法

标签 c++ templates overloading pointer-to-member overload-resolution

考虑 the following code :

struct A {
    int& getAttribute();
    const int& getAttribute() const;
};

std::vector<int> foo(const std::vector<A>& as) {
    std::vector<int> ints;
    std::transform(as.begin(), as.end(), std::back_inserter(ints),
                   std::mem_fn(&A::getAttribute));
    return ints;
}

它的编译(g++ -std=c++14 -c mem_fn.cpp,g++ 版本 7.5.0)失败并出现以下错误:

error: no matching function for call to
‘mem_fn(<unresolved overloaded function type>)’

但是,

  • 如果我们keep只有 const int& getAttribute() const method,编译成功
  • 如果我们keep只有 int& getAttribute()方法,编译失败并显示以下错误消息:
    /usr/include/c++/7/bits/stl_algo.h:4306:24:
         error: no match for call to
         ‘(std::_Mem_fn<int& (A::*)()>) (const A&)’
    /usr/include/c++/7/functional:174:27:
         error: no matching function for call to
         ‘__invoke(int& (A::* const&)(), const A&)’
    /usr/include/c++/7/bits/invoke.h:89:5:
         error: no type named ‘type’ in
         ‘struct std::__invoke_result<int& (A::* const&)(), const A&>’
    

或者,我们可以在这里使用 lambda 或通过 explicitly specifying 帮助编译器匹配方法的类型为 mem_fn的模板参数: std::mem_fn<const int& () const>(&A::getAttribute) .

所以,它看起来像 int& getAttribute()方法不适合,const int& getAttribute() const方法是编译器在原始代码中应该选择的方法。 为什么编译器无法选择它并报告 <unresolved overloaded function type>错误?

最佳答案

编译器应该在创建mem_fn 时选择函数的指针。它只能查看 std::mem_fn(&A::getAttribute) 表达式,但无法查看其使用方式。可以使用 user-defined conversion operators 解决, 但通常不会完成。

因此,您关于此 mem_fn future 用途的推理不适用。

您必须指定要使用的 &A::getAttribute 的确切重载。 static_cast 到固定类型将起作用(这是允许未解析的重载函数的特殊情况):

  std::transform(
      as.begin(), as.end(), std::back_inserter(ints),
      std::mem_fn(static_cast<const int &(A::*)() const>(&A::getAttribute)));

关于c++ - 编译器无法解析通过 std::mem_fn 传递的匹配类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67408619/

相关文章:

c++ - 将具有默认参数的 lambda 函数复制到变量

c++ - 我想在 Cygwin64 终端上输入 "g++"而不是 "i686-pc-cygwin-g++"?

c++ - 委托(delegate)给子组件的模式

c++ - 使用参数包作为模板类的类型名

java - 设置具有相同的删除,但都不会覆盖另一个错误

函数中的 C++ const 关键字

c++ - 是否有任何库可以像 Open CV 访问摄像头一样访问 PC(Windows)麦克风?

C++ 使用 lambda 函数作为模板函数特化

types - 如何实现 _() 方法?

java - 从Java中的泛型方法调用重载方法