#include <iostream>
#include <functional>
#include <string>
#include <cmath>
using namespace std;
template <typename numtype>
int foo(string index, const function<void(numtype)>& lambada){
cout << "before callback" << endl;
lambada(index);
return 0;
}
template <typename numtype>
//定义callback函数,返回函数类型function<void(numtype &)>,即下面的lambda的函数类型
function<void(numtype &)> callback(int cnt) {
//定义lambda函数,返回值为void,入参为index,捕获值cnt
auto lambda = [cnt](numtype& index) -> void{//
cout << index.size() * cnt << endl;
return;
};
return lambda;
}
int main()
{
string index = "12";
int cnt = 4;
//std::function调用模板函数对象需要添加typename
cout << foo(index, callback<string>(cnt)) << endl;
return 0;
}
输出为
test$ g++ -g test.cc -o test
test$ ./test
before callback
8
0
test$