【发布时间】:2018-04-12 14:40:31
【问题描述】:
我有简单的map 实现和简单的id(身份):
template <typename T>
T map(const T& x, std::function<decltype(x[0])(decltype(x[0]))> f) {
T res(x.size());
auto res_iter = begin(res);
for (auto i(begin(x)); i < end(x); ++i) {
*res_iter++ = f(*i);
}
return res;
}
template <typename T>
T id(T& x) {return x;}
当我打电话时
vector<int> a = {1,2,3,4,5,6,7,8,9};
map(a, id<const int>);
它有效,但我想在没有类型说明的情况下调用它,如下所示:
map(a, id);
当我这样做时,我得到了错误:
error: cannot resolve overloaded function 'id' based on conversion to type 'std::function<const int&(const int&)>'
map(a, id);
^
当错误包含右有界类型时,我该如何解决?为什么编译器不能从 map 的上下文中推断出 id 的类型?
【问题讨论】:
-
我将把我之前未回答的有用部分变成评论:通常最好为函数输入(以及类型签名的文档)提供一个普通模板参数,而不是
std::function。它不能解决问题,但类似于:template<typename T, typename F> T map(const T& x, F&& f)。像 std::function 这样的东西在这里会很棒 if C++ 类型推断走得更远。
标签: c++ templates c++14 generic-programming