I've actually figured out how to do what the title to my question suggests, but not in a satisfactory and portable way. Let me be more specific.
This is a stripped down and modified version of my code:
#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;
}
Now, my issue is that this code compiles and works fine in Windows 7 with Microsoft Visual Studio C++ 2008, but not in Red Hat linux with g++ ( version 4.1.2 20080704 ), where I get the following error:
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]
In linux it compiles and works fine if I replace the mem_fun()
call with this: mem_fun( static_cast<int (A::*)() const>(&A::my_val) )
. However I find this solution less aesthetically pleasing than the first one. Is there another portable way to do what I want? (Perhaps there's an obvious simple way to do this and I'm just making a big fuss over it...)
Thank you in advance. -Manuel