繁体   English   中英

C ++强制mem_fun选择特定的重载成员函数

[英]C++ forcing mem_fun to select a specific overloaded member function

我实际上已经弄清楚如何做我的问题的标题所暗示的,但不是以令人满意和便携的方式。 让我更具体一点。

这是我的代码的精简版和修改版:

#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进行编译和工作正常,但在使用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) ) 但是我觉得这个解决方案比第一个解决方案更不美观。 还有另一种便携式方式可以做我想要的吗? (也许有一种明显的简单方法可以做到这一点,我只是对它做了大惊小怪......)

先感谢您。 -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(), a.end(), inserter( b, b.end() ),
        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(), a.end(), inserter( b, b.end() ), std::mem_fun(my_val) );
    return b;
}
typedef int (A::*MethodType)() const;
const_mem_fun(MethodType(&A::my_val));

这是个主意。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM