【发布时间】:2020-08-16 16:23:17
【问题描述】:
我想编写一个函数,它接受任何类型的通用容器并打印它。
让我们暂时离开它不适用于某些关联容器并专注于这个问题:
template<template<typename> typename Cont, typename T>
void print(const Cont<T>& cont)
{
for (const auto it : cont)
{
cout << it << " ";
}
cout << endl;
}
int main()
{
vector<string> v;
print(v);
}
错误状态:
error C2672: 'print': no matching overloaded function found
error C3207: 'print': invalid template argument for 'Cont', class template expected
谁能解释一下为什么编译器不能在这里推断出类型?
即使我明确声明print<vector<string>>(v)?
【问题讨论】:
-
您不需要模板模板参数。
template <typename Cont> void print(const Cont& cont) {...}也可以。 -
如果你看到例如this
std::vectorreference 你会看到它有 两个 模板参数,而不是你指定的一个。并且不同的标准容器有不同数量的模板参数。
标签: c++ c++11 templates function-templates template-templates