C强制mem_fun选择特定的重载成员函数
发布时间:2020-12-16 06:59:08 所属栏目:百科 来源:网络整理
导读:我实际上已经弄清楚如何做我的问题的标题所暗示的,但不是以令人满意和便携的方式.让我更具体一点. 这是我的代码的精简版和修改版: #include algorithm#include functionalclass A {public: int my_val() const { return _val; }; int my_val() { throw "Can
我实际上已经弄清楚如何做我的问题的标题所暗示的,但不是以令人满意和便携的方式.让我更具体一点.
这是我的代码的精简版和修改版: #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; } 现在,我的问题是这个代码在Windows 7中使用Microsoft Visual Studio C 2008进行编译和工作正常,但在Red Hat linux中没有g(版本4.1.2 20080704),我得到以下错误: 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)).但是我觉得这个解决方案比第一个解决方案更不美观.还有另一种便携式方式可以做我想要的吗? (也许有一种明显的简单方法可以做到这一点,我只是对它做了大惊小怪……) 先感谢您. 解决方法
我不确定你,但这对我来说会更令我满意.定义自己的功能:
template <typename S,typename T> inline std::const_mem_fun_t<S,T> const_mem_fun(S (T::*f)() const) { return std::const_mem_fun_t<S,T>(f); } 并像这样使用它: std::vector<int> get_int_vector(const std::vector<A*>& a) { std::vector<int> b; b.reserve(a.size()); transform( a.begin(),const_mem_fun(&A::my_val) ); return b; } 避免演员的另一种选择是这样的: std::vector<int> get_int_vector(const std::vector<A*>& a) { std::vector<int> b; b.reserve(a.size()); int& (A::*my_val)() const = &A::my_val; transform( a.begin(),std::mem_fun(my_val) ); return b; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |