C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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

解决方法@H_301_28@
我不确定你,但这对我来说会更令我满意.定义自己的功能

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,请注明来意。