samedi 28 octobre 2017

How to write std::bind with constructor

Given this setup (the vector is guaranteed to be initially empty)

typedef vector<list<int>> V;
V v;

I want to create a partial application like this:

auto f = [&v](int value) { v.push_back(list<int> { value }); };

Unfortunately, in our working environment, we can't use lambda (with gcc 4.4). Can anyone help me writing an equivalent version using std::bind?

So far I come up with several attempts (using Visual Studio):

1.

auto f = bind<void (V::*)(const V::value_type&)>(&V::push_back, &v, list<int>(1, placeholders::_1));

with error

'<function-style-cast>': cannot convert from 'initializer list' to 'std::list<int,std::allocator<_Ty>>'

2.

auto f = bind<void (V::*)(const V::value_type&)>(&V::push_back, &v, list<int>::list(1, placeholders::_1));

with error

'std::list<int,std::allocator<_Ty>>::list': none of the 10 overloads could convert all the argument types

3.

auto f = bind<void (V::*)(const V::value_type&)>(&V::push_back, &v, list<int> { placeholders::_1 });

with error

'initializing': cannot convert from 'initializer list' to 'std::list<int,std::allocator<_Ty>>'

4.

auto f = bind<void (V::*)(const V::value_type&)>(&V::push_back, &v, list<int> { (const int&) placeholders::_1 });

this compiles, but the vector created by f(10) would have a list with the first element equals to 0, not 10. It looks like the list is a default created one.

Aucun commentaire:

Enregistrer un commentaire