C++ Primer 5th笔记(10)chapter10 泛型算法 :bind
生活随笔
收集整理的這篇文章主要介紹了
C++ Primer 5th笔记(10)chapter10 泛型算法 :bind
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1. 定義
一個(gè)函數(shù)適配器,接受一個(gè)函數(shù)調(diào)用,增加或更改參數(shù)傳遞給另外一個(gè)函數(shù)調(diào)用。
比如 auto newCallable=bind(callable, arg_list);
newCallable本身是一個(gè)可調(diào)用對(duì)象,當(dāng)我們調(diào)用newCallable函數(shù)時(shí), newCallable會(huì)調(diào)用callable函數(shù)。
arg_list是callable的參數(shù),是逗號(hào)分隔的多個(gè)參數(shù)列表,形如_n的名字,_1是newCallable的第一個(gè)參數(shù), _2為第二個(gè)參數(shù),依次類推。
- 標(biāo)準(zhǔn)庫(kù)bind函數(shù) functional.h
- _n參數(shù)在命名空間placeholders中,需要如下聲明:
eg.
using namespace std::placeholders; bool check_size(const string &s, string::size_type sz) {return s.size() >= sz; }auto check6 = bind(check_size, _1, 6); string s = "hello"; bool b1 = check6(s); <=> check_size(s, 6);eg2.
auto g = bind(f, a, b, _2, c, _1); g(_1, _2) => f(a, b, _2, c, _1); g(X, Y) => f(a, b, Y, c, X);2. bind參數(shù)不能拷貝
2.1 eg. 不能拷貝ostream
ostream &print(ostream &os,const string &s,char c) { return os<<s<<c;}for_each(word.begin(),word.end(),bind(print,os,_1, ''))//error2.2 可以使用ref函數(shù)。
函數(shù)ref返回一個(gè)對(duì)象,包含給定引用,此對(duì)象是可以拷貝的。
- 標(biāo)準(zhǔn)庫(kù)中還有一個(gè)cref函數(shù),生成一個(gè)保存const引用的類。
- 與bind一樣,函數(shù)ref和cref也定義在頭文件functional中。
總結(jié)
以上是生活随笔為你收集整理的C++ Primer 5th笔记(10)chapter10 泛型算法 :bind的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ Primer 5th笔记(10)
- 下一篇: s3c2440移植MQTT