更新时间:2023-11-02 18:40:16
假设您使用键
c $ c> value 意味着是placeholers,不能使用关键字 typename
来声明模板参数。也就是说, Foo< typename T>
总是无效的,但不能被 Foo< typename T :: bar& code>这是完全不同的。专用化语法如下:
Assuming your uses of key
and value
are meant to be placeholers, you cannot declare template parameters inline with the keyword typename
. That is to say, Foo<typename T>
is always invalid -- but not to be mistaken with Foo<typename T::bar>
which is different altogether. The syntax for specialization looks like:
// Declare template parameters up front
template<typename Key, typename Value>
std::ostream&
printFormatted<std::map<Key, Value> >(std::map<Key, Value> const& container, std::ostream& os = std::cout);
但这不会工作,因为它是一个部分不允许用于函数模板。使用重载:
but that wouldn't work because it's a partial specialization and those are not allowed for function templates. Use overloading instead:
template<typename Key, typename Value>
std::ostream&
printFormatted(std::map<Key, Value> const& container, std::ostream& os = std::cout);
此重载将优先于更一般的模板。
This overload will be preferred over the more general template.