Using std :: tr1 :: bind with std :: vector :: push_back

Why my VS2010 cannot 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;
}
+2
source share
4 answers

Try the following:

struct push_back {
    void
    operator()(std::vector<int>& vector, int i) const
    {
        vector.push_back(i);
    }
};

// somewhere else:
std::vector<int> vec;
std::tr1::bind(push_back(), std::tr1::ref(vec), 1)();

With C ++ 03, note that push_backit cannot be a local type; with C ++ 11 it can, but it would be more idiomatic (and completely equivalent) to use lambda.

In all likelihood, your implementation provides overloads for std::vector<T>::push_back, and therefore its address must be eliminated. If so, your compiler should provide you with the appropriate error message. In all cases, you must explain what you mean by "this is impossible."


It's not about using such a helper function. - purple

? .

:

std::vector<int> vec;
void (std::vector<int>::*push_back)(int const&) = &std::vector<int>::push_back;
std::tr1::bind(push_back(), std::tr1::ref(vec), 1)();

, .

+3

, .

#include <iostream>
#include <tr1/functional>
#include <vector>

int main(int argc, char* argv[]) {
    std::vector<int> vec;
    std::tr1::bind(&std::vector<int>::push_back, std::tr1::ref(vec), 1)();
    std::cout << "vec.size = " << vec.size() << std::endl;
    std::cout << "vec[0] = " << vec[0] << std::endl;
    return 0;
}

$ gcc -o test -lstdc++ test.cpp && ./test
vec.size = 1
vec[0] = 1

: , push_back. . boost:: bind VS2010?. , push_back, . Visual Studio 2010 boost:: bind.

+5

, , , ++. std::vector<>::push_back ++ 11, , , lvalues ​​ rvalues.

, -, §13.4/1 ++ 11 FDIS , , :

, - . . - , , . [. , , ---. -end note]

  • ,
  • ,
  • ,
  • ,
  • , ,
  • -.

&. , . [: , , . -end note]

§17.6.5.5/2:

- - , -; , , - ++ .

Therefore, it does not ever carry the address of a standard member function of a library class, since the type of such an expression is, by definition, unrecognizable, with the exception of the implementation by-implementation.

Luke Danton suggested a workaround (in particular, using lambda), I would also recommend:

std::vector<int> vec;
[&](){ vec.push_back(1); }();
+4
source

This should be convenient:

std::vector<int> vec;
std::tr1::bind(&std::vector<int>::push_back, std::tr1::ref(vec), _1)(1);
0
source

All Articles