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

C++ forcing mem_fun to select a specific overloaded member function

本文关键字:一个 重载 函数 成员 mem 强制 fun 选择 C++      更新时间:2023-10-16

我实际上已经想好了如何按照问题的标题进行处理,但不是以一种令人满意和可移植的方式。让我更具体一点。

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

#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++的Red Hat linux(版本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(), 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));

这就是想法。

相关文章: