【发布时间】:2021-05-05 20:54:04
【问题描述】:
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方法,编译成功 - 如果我们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>错误?
【问题讨论】:
标签: c++ templates overloading member-function-pointers overload-resolution