惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
V
Visual Studio Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
量子位
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
T
Tailwind CSS Blog
GbyAI
GbyAI
爱范儿
爱范儿
Y
Y Combinator Blog
宝玉的分享
宝玉的分享
有赞技术团队
有赞技术团队
罗磊的独立博客
Recent Announcements
Recent Announcements
博客园 - 司徒正美
M
MIT News - Artificial intelligence
小众软件
小众软件
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
B
Blog RSS Feed
A
About on SuperTechFans
Hugging Face - Blog
Hugging Face - Blog
Apple Machine Learning Research
Apple Machine Learning Research
雷峰网
雷峰网

博客园 - shootingstars

硬件相关概念 我的Function C的可变参数 C++概念网摘 Mifare 串行读取协议 韦根协议 学习C的可变参数 关于汇编程序调用各种C函数的例子 如何移植Java的类中的super到C++代码中 编译原理学习 使用python编写每日构建工具 boost::regex学习(5) - shootingstars - 博客园 boost::regex学习(4) - shootingstars - 博客园 boost::regex学习(3) boost::regex学习(2) 《世界大战》《变形金刚》观后感 boost::regex学习(1) boost::algorithm学习 五种迭代器
关于标准库中的ptr_fun/binary_function/bind1st/bind2nd
shootingstars · 2007-08-17 · via 博客园 - shootingstars

以前使用bind1st以及bind2nd很少,后来发现这两个函数还挺好玩的,于是关心上了。
在C++ Primer对于bind函数的描述如下:

绑定器binder通过把二元函数对象的一个实参绑定到一个特殊的值上将其转换成一元函数对象

C++标准库提供了两种预定义的binder 适配器bind1st 和bind2nd 正如你所预料的bind1st 把值绑定到二元函数对象的第一个实参上bind2nd 把值绑定在第二个实参上
例如
为了计数容器中所有小于或等于10 的元素的个数我们可以这样向count_if()传递
count_if( vec.begin(), vec.end(), bind2nd( less_equal<int>(), 10 ));

哦,这倒是挺有意思的。于是依葫芦画瓢:

bool print(int i, int j) 
{
    std::cout
<< i << "---" << j << std::endl; 
    
return i>j;
}
int main(int argc, char *argv[])
{
    (std::bind1st(print, 
2))(1);
    
return 0;

}

满怀希望它能够打印
2---1

只不过。。。编译出错:
1    Error    error C2784: 'std::binder1st<_Fn2> std::bind1st(const _Fn2 &,const _Ty &)' : could not deduce template argument for 'overloaded function type' from 'overloaded function type'   
---不能够推断出模板参数for 'overloaded function type' from 'overloaded function type' 。。。。
(还真看不明白。。。)

于是直接看bind1st代码:

template<class _Fn2,
    
class _Ty> inline
    binder1st
<_Fn2> bind1st(const _Fn2& _Func, const _Ty& _Left)
        {    
        typename _Fn2::first_argument_type _Val(_Left);
        
return (std::binder1st<_Fn2>(_Func, _Val));
        }

嗯。。。在代码里
typename _Fn2::first_argument_type _Val(_Left)
说必须定义
first_argument_type类型,可是我一个函数,哪里来的这个类型定义?嗯,STL一定提供了某种东东用来自动定义这个类型。找啊找,于是找到了ptr_fun。
这个函数自动将一个函数指针转换为一个binary_function的继承类pointer_to_binary_function,而在
binary_function中定义了first_argument_type。
于是修改代码:

int main(int argc, char *argv[])
{
    (std::bind1st(std::ptr_fun(print), 
2))(1);
    
return 0;
}

打印结果如下:
2---1