大佬教程收集整理的这篇文章主要介绍了C强制mem_fun选择特定的重载成员函数,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
#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)).但是我觉得这个解决方案比第一个解决方案更不美观.还有另一种便携式方式可以做我想要的吗? (也许有一种明显的简单方法可以做到这一点,我只是对它做了大惊小怪……)
先感谢您.
-Manuel
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; }
以上是大佬教程为你收集整理的C强制mem_fun选择特定的重载成员函数全部内容,希望文章能够帮你解决C强制mem_fun选择特定的重载成员函数所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。