在
this article,提供以下代码:
std::vector<int> ivec = { 1,2,3,4}; std::vector<std::string> svec = { "red","green","blue" }; auto adder = [](auto op1,auto op2){ return op1 + op2; }; std::cout << "int result : " << std::accumulate(ivec.begin(),ivec.end(),adder) << "\n"; std::cout << "string result : " << std::accumulate(svec.begin(),svec.end(),std::string(""),adder) << "\n";
如果我理解正确,编译器会生成一个类似于这样的内部类:
template<class T> class _lambda { public: T operator()(T lhs,T rhs) { return lhs + rhs; } };
但是我不明白的是,在代码的这一部分中,加法器在同一时间似乎有两种类型:_lambda< int>和_lambda< string> ;.这怎么可能?
解决方法
根据标准5.1.2 / p5 Lambda表达式[expr.prim.lambda]:
For a generic lambda,the closure type has a public inline function
call operator member template (14.5.2) whose template-parameter-list
consists of one invented type template-parameter for each occurrence of
auto in the lambda’s parameter-declaration-clause,in order of
appearance.
因此,实际产生的是:
class _lambda { public: template<typename T1,typename T2> auto operator()(T1 lhs,T2 rhs) const { return lhs + rhs; } };