我习惯了 struct hash<template class Key>
形式的模板语法。但是使用时有什么区别template <> struct hash<Key>
?
namespace std {
template <>
struct hash<Key>
{
std::size_t operator()(const Key& k) const
{
....
}
};
}
请注意,我确实搜索了
template <>
的含义。我理解(我希望)这是一种方式,当使用模式匹配来指定不匹配的情况时,但与 struct<Key>
的用法一起使用我不明白它的动机。
最佳答案
有不同级别的模板特化:
1) 模板声明(无特化)
template <class Key, class Value>
struct Foo {};
2) 部分特化
template <class Key>
struct Foo<Key, int> {};
3) 完全/明确的特化
template <>
struct Foo<std::string, int> {};
然后,在实例化模板时,编译器将选择可用的最专业的定义:
Foo<std::string, std::string> f1; // Should match #1
Foo<int, int> f2; // Should match #2
Foo<std::string, int> f3; // Should match #3
#1 和 #3 也适用于模板函数。
关于templates - 带有空括号和结构的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38467025/