C++之可调用对象
C++中的可调用对象分为以下几种:
- 函数
- 函数指针
- lambda表达式
- bind创建的对象
- 重载了函数调用运算符(即“()”)的类
这里通过例子说明一下lambda表达式与重载了函数调用运算符的类有一些相通之处。
lambda是函数对象,是一个可调用对象。编译器在解释lambda表达式时,将其解释为一个未命名类的未命名对象,该类重载了函数调用运算符。
1、首先声明一个类,重载函数调用运算符。成员变量根据实际情况而定。
/*** 重载了函数调用运算符的类*/classSizeComp{public:SizeComp(std::size_t sz): size(sz){}voidoperator()(const string & str)const{if(str.size()>= size){cout << str << endl;}}private:std::size_t size;};
2、创建类对象,并给需要用到的变量进行赋值。
void testInvoke2nd(){vector<string> strVec ={"1","12","123","1234","12345","123456","1234567"};std::size_t sz =5;cout <<"lambda表达式:"<< endl;auto comp =[sz](const string & str)->void{if(str.size()>= sz){cout << str << endl;}};for_each(strVec.begin(), strVec.end(), comp);cout <<"()运算符重载:"<< endl;for_each(strVec.begin(), strVec.end(),SizeComp(sz)); // 先是调用构造函数创建一个临时对象}
对可调用对象的使用
#include<iostream>#include<functional>#include<map>usingnamespace std;/**< 可调用对象——函数 *//*** 若进行函数重载则不能直接使用函数名* 会产生二义性* 此时考虑函数指针或其他的实现方式*///implements "+" operationconstint addInt(constint x,constint y){return x + y;}/**< 可调用对象——重载了调用运算符的类 *///implements "-" operationstruct minusInt{constintoperator()(constint x,constint y){return x - y;}};//函数指针所指向的函数constint dividesFunc(constint x,constint y){return x / y;}void testFunction(){/**< 可调用对象——lambda表达式 *///implements "*" operationauto multipInt =[](constint x,constint y)->constint{return x * y;};/**< 可调用对象——函数指针 *///implements "/" operationconstint(*dividesInt)(int,int)= dividesFunc;// dividesInt = multipInt; // 说明lambda是一个函数对象/*** function<int(int, int)>的原型是function<T>* @brief 存储可调用对象(该对象的调用形式应该与T相同)* @param T 函数类型(返回值类型,参数个数及)*/map<string, function<int(int,int)>> binops ={{"+", addInt},/* 函数名默认转化为函数指针类型 */{"-", minusInt()},/* 创建一个类对象 */{"*", multipInt},/* lambda表达式类型的对象 */{"/", dividesInt}/* 函数指针 */};cout << binops["+"](10,5)<< endl<< binops["-"](10,5)<< endl<< binops["*"](10,5)<< endl<< binops["/"](10,5)<< endl;}int main(){testFunction();return0;}

浙公网安备 33010602011771号