小编wol*_*ang的帖子

如何推导Lambda的返回类型?

我想模仿map()C ++中的Ruby 方法。我正在努力自动找出返回类型:

#include <vector>
#include <string>
#include <algorithm>
#include <iostream>

typedef std::string T2;

template<class T1,
//  class T2, // gives "couldn't deduce template parameter 'T2'"
    class UnaryPredicate>
std::vector<T2> map(std::vector<T1> in, UnaryPredicate pred)
{
    std::vector<T2> res(in.size());
    std::transform(in.begin(), in.end(), res.begin(), pred);
    return res;
}

int main()
{
    std::vector<int> v1({1,2,3});
    auto v2(map(v1, [](auto el) { return "'"+std::to_string(el+1)+"'"; }));
    std::cout << v2[0] << "," << v2[1] << "," << v2[2] << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这样可以编译,但T2固定为string。如果使用其他T2定义,编译器会抱怨couldn't …

c++ lambda templates template-argument-deduction generic-lambda

5
推荐指数
1
解决办法
103
查看次数