Why my VS2010 can't compile this code:
#include <functional>
#include <vector>
int main()
{
std::vector<int> vec;
std::bind(&std::vector<int>::push_back, std::ref(vec), 1)();
return 0;
}
Why my VS2010 can't compile this code:
#include <functional>
#include <vector>
int main()
{
std::vector<int> vec;
std::bind(&std::vector<int>::push_back, std::ref(vec), 1)();
return 0;
}
The bottom line is that what you're trying to do isn't possible in portable C++.
std::vector<>::push_back
is guaranteed to be overloaded in C++11 compilers, as at a minimum there must be an overload for lvalues and an overload for rvalues.Usually, when taking the address of an overloaded member function, §13.4/1 in the C++11 FDIS tells us that we can control which overload we're taking the address of thusly:
The problem comes from §17.6.5.5/2:
Consequently, it is not portable to ever take the address of a standard library class member function, as the type of such an expression is by definition unknowable except on an implementation-by-implementation basis.
Luc Danton's proposed workaround (specifically, using a lambda) is also what I would recommend:
You should be more specific why this doesn't seem to work for you.
Update: Luc Danton is right, the issue here is the overloaded
push_back
. See question Are there boost::bind issues with VS2010 ?. Also, note that the issue is not limited topush_back
, see Visual Studio 2010 and boost::bind.It should propably lok like this:
Try this:
With C++03 note that
push_back
cannot be a local type; with C++11 it can but it would be more idiomatic (and completely equivalent) to use a lambda.In all likeliness your implementation provides overloads for
std::vector<T>::push_back
and thus its address would have to be disambiguated. If this is what happened, your compiler should have provided you with an appropriate error message. In all cases, you should explain what you mean by "it's not possible".Then why didn't you put it in the question? I can't read your mind.
You can also try this:
Which I believe is not guaranteed to success.