首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用bind1st和bind2nd?

如何使用bind1st和bind2nd?
EN

Stack Overflow用户
提问于 2009-09-13 20:26:41
回答 2查看 21.2K关注 0票数 16

我想学习如何使用绑定函数。这就是我的想法:我有这个函数,它接受参数:

代码语言:javascript
复制
void print_i(int t, std::string separator)
{
        std::cout << t << separator;
}

我想做的是:

代码语言:javascript
复制
std::vector<int> elements;
// ...
for_each(elements.begin(), elements.end(), std::bind2nd(print_i, '\n'));

但是它不起作用!

下面是我得到的结果:

代码语言:javascript
复制
/usr/include/c++/4.3/backward/binders.h: In instantiation of ‘std::binder2nd<void ()(int, std::string)>’:
main.cpp:72:   instantiated from here
/usr/include/c++/4.3/backward/binders.h:138: error: ‘void ()(int, std::string)’ is not a class, struct, or union type
/usr/include/c++/4.3/backward/binders.h:141: error: ‘void ()(int, std::string)’ is not a class, struct, or union type
/usr/include/c++/4.3/backward/binders.h:145: error: ‘void ()(int, std::string)’ is not a class, struct, or union type
/usr/include/c++/4.3/backward/binders.h:149: error: ‘void ()(int, std::string)’ is not a class, struct, or union type
/usr/include/c++/4.3/backward/binders.h:155: error: ‘void ()(int, std::string)’ is not a class, struct, or union type
/usr/include/c++/4.3/backward/binders.h:140: error: field ‘std::binder2nd<void ()(int, std::string)>::op’ invalidly declared function type
/usr/include/c++/4.3/backward/binders.h: In function ‘std::binder2nd<_Operation> std::bind2nd(const _Operation&, const _Tp&) [with _Operation = void ()(int, std::string), _Tp = char]’:
main.cpp:72:   instantiated from here
/usr/include/c++/4.3/backward/binders.h:164: error: ‘void ()(int, std::string)’ is not a class, struct, or union type
/usr/include/c++/4.3/bits/stl_algo.h: In function ‘_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, _Funct = std::binder2nd<void ()(int, std::string)>]’:
main.cpp:72:   instantiated from here
/usr/include/c++/4.3/bits/stl_algo.h:3791: error: no match for call to ‘(std::binder2nd<void ()(int, std::string)>) (int&)’
make: *** [all] Error 1

我可以使用functor,但使用绑定会更快。

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-09-13 20:35:05

bind2nd的参数必须是AdaptableBinaryFunction。普通的二进制函数不能满足这一要求(自适应函数需要typedefs作为其返回和参数类型,普通函数类型不提供任何typedefs)。您可以使用std::bind,这可能是更好的选择。

票数 11
EN

Stack Overflow用户

发布于 2018-08-27 22:21:42

这些函数从C++11开始就被弃用了,并且在C++17中被删除了。正如上面的一条评论所提到的,现在更好的解决方案是使用std::bind和占位符:

代码语言:javascript
复制
void callable(int a, int b);
auto f = std::bind1st(&callable, 42); // returns a 1-arg function

变成:

代码语言:javascript
复制
// returns a 1-arg function
auto f = std::bind(&callable, 42, std::placeholders::_1);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1418756

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档