考虑 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/