gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:19:24 27 4
gpt4 key购买 nike

我实际上已经想出了如何按照我的问题标题建议的那样做,但不是以令人满意和便携的方式。让我说得更具体一些。

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

#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++(版本 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) ) .然而,我发现这个解决方案不如第一个在美学上令人愉悦。还有另一种可移植方式来做我想做的事吗? (也许有一个明显的简单方法可以做到这一点,而我只是大惊小怪...)

提前致谢。-曼纽尔

最佳答案

我不确定你的看法,但这对我来说会更令人高兴。定义你自己的函数:

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;
}

关于C++ 强制 mem_fun 选择特定的重载成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9569692/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com