【发布时间】:2020-09-05 13:39:19
【问题描述】:
我有以下代码示例:
template<typename T>
void print(T t) {
std::cout << t << std::endl;
}
template<typename Key, typename Value, typename F>
void traverse(std::map<Key, Value>& m, F f) {
for (auto&& [key, value] : m) {
f(value);
}
}
int main()
{
std::map<int, std::string> M;
// initializing the map
traverse(M, print);
}
这里编译器出错并显示以下消息:
could not deduce template argument for 'F'
显式的traverse(M, print<std::string>); 解决了这个问题。
我的问题真的是为什么编译器不能推断打印函数的模板类型?
据我了解,所有的编译时间信息都是可用的。
【问题讨论】:
-
我没有参考标准,但我认为模板参数推导发生在实例化之前(为了 SFINAE 和其他东西工作)。
-
函数模板不是函数。您要求编译器推断生成具有不同类型的函数的工厂的类型。例如。
print<string>的类型为void(string),而print<double>的类型为void(double)。作为模板,print本身没有类型。因此编译器无法推断其类型。 -
如果您改为使用
auto print = [](auto t){ std::cout << t << std::endl; },那么您将拥有F的可推导类型(然后在调用时推导std::string)
标签: c++ templates c++17 type-deduction