相关疑难解决方法(0)

编译器不推导出模板参数(map std :: vector - > std :: vector)

我有以下模板.

template<typename T, typename U>
std::vector<U> map(const std::vector<T> &v, std::function<U(const T&)> f) {
    std::vector<U> res;
    res.reserve(v.size());
    std::transform(std::begin(v), std::end(v), std::end(res), f);
    return res;
}
Run Code Online (Sandbox Code Playgroud)

当我在我的代码中使用它时,我指定了模板参数.为什么编译器无法为我推断出这个?如何更改模板定义以使其工作?

vector<int> numbers = { 1, 3, 5 };

// vector<string> strings = map(numbers, [] (int x) { return string(x,'X'); });

vector<string> strings = map<int, string>(numbers, [] (int x) { return string(x,'X'); });
Run Code Online (Sandbox Code Playgroud)

可运行代码:http://ideone.com/FjGnxd

这个问题中的原始代码来自:std :: transform-like函数返回转换后的容器

c++ templates vector std c++11

9
推荐指数
1
解决办法
801
查看次数

标签 统计

c++ ×1

c++11 ×1

std ×1

templates ×1

vector ×1