如何用构造函数编写std :: bind

时间:2017-10-29 00:43:17

标签: c++ c++11 functional-programming

编辑:我知道我可以创建一个命名函数来解决问题。我只是想从你的专家那里学习一些神秘的C ++模板语法。

鉴于此设置(保证向量最初为空)

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

我想创建一个像这样的部分应用程序:

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

不幸的是,在我们的工作环境中,我们不能使用lambda(使用gcc 4.4)。任何人都可以帮助我使用std::bind编写等效版本吗?

到目前为止,我想出了几次尝试(使用Visual Studio):

1

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

有错误

'<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));

有错误

'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 });

有错误

'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 });

这个编译,但f(10)创建的向量将有一个列表,第一个元素等于0,而不是10.看起来列表是默认创建的列表。

1 个答案:

答案 0 :(得分:0)

当std :: bind是boost :: bind或boost :: lambda :: bind时,有一个boost :: lambda :: constructor来绑定构造函数。

std :: bind有点受限制,它不能做一些boost :: bind或boost :: lambda :: bind的事情。从标准的角度来看,它应该不是一个大问题,因为使用C ++ 11你应该有C ++ 11 lambdas。