【发布时间】:2012-03-05 15:55:08
【问题描述】:
我实际上已经想出了如何按照我的问题标题所暗示的方式去做,但不是以一种令人满意和便携的方式。让我更具体一点。
这是我的代码的精简和修改版本:
#include <algorithm>
#include <functional>
class A {
public:
int my_val() const { return _val; };
int& my_val() { throw "Can't do this"; };
// My class is actually derived from a super class which has both functions, but I don't want A to be able to access this second version
private:
int _val;
}
std::vector<int> get_int_vector(const std::vector<A*>& a) {
std::vector<int> b;
b.reserve(a.size());
transform( a.begin(), a.end(), inserter( b, b.end() ),
std::mem_fun<int, const A>(&A::my_val) );
return b;
}
现在,我的问题是这段代码在带有 Microsoft Visual Studio C++ 2008 的 Windows 7 中编译和运行良好,但在带有 g++(版本 4.1.2 20080704)的 Red Hat linux 中却没有,我收到以下错误:
error: call of overloaded 'mem_fun(<unresolved overloaded function type>)' is ambiguous
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h:713: note: candidates are: std::mem_fun_t<_Ret, _Tp> std::mem_fun(_Ret (_Tp::*)()) [with _Ret = int, _Tp = const A]
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_function.h:718: note: std::const_mem_fun_t<_Ret, _Tp> std::mem_fun(_Ret (_Tp::*)()const) [with _Ret = int, _Tp = const A]
在 linux 中,如果我将 mem_fun() 调用替换为:mem_fun( static_cast<int (A::*)() const>(&A::my_val) ),它可以编译并正常工作。然而,我发现这个解决方案不如第一个解决方案美观。有没有另一种便携的方式来做我想做的事? (也许有一种明显简单的方法可以做到这一点,我只是在大惊小怪......)
提前谢谢你。 -曼努埃尔
【问题讨论】:
标签: c++ member-function-pointers mem-fun