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;
}
现在,我的问题是,这段代码在带有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));
这就是想法。
相关文章:
- 一个关于在C++中重载布尔运算符的问题
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 运算符重载:"operator+"必须采用零个或一个参数
- 重载运算符*以获取对另一个类的实例的引用
- 我重载了 << 和 = 运算符。为什么当我将一个对象分配给另一个对象并尝试打印它时,我会被打印出来?
- MSVC 错误:4 个重载中的任何一个都无法转换所有参数类型
- 为什么我得到 C2883:函数声明与 - 在仅覆盖基类中的一个重载时通过使用 - delcaration 引入
- 尝试将节点插入链表中,但我需要一个重载运算符<函数
- 如果存在可以匹配另一个重载函数的函数模板,将调用哪个函数
- 根据可用的参数使用一个或另一个重载的创建者
- 重载运算符试图将另一个重载运算符作为参数
- 当涉及一个重载函数作为实参时,模板实参推导是如何工作的
- 我正在努力完成我的作业.在Distance类中创建一个重载*操作符
- 当派生类中存在另一个重载时,无法调用基类的方法
- C++ - 链接器找不到我的函数,它恰好是一个重载运算符
- 将类构造函数重载放在同一类的另一个重载中
- 可以在c++中调用另一个重载构造函数吗?
- 定义一个重载函数的类型