templates - 带有空括号和结构的模板特化

标签 templates c++11

我习惯了 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/

相关文章:

c++ - 如何使用模板化构造函数调用 make_shared 或 make_unique

c++ - 为什么在某些 STL 容器中我们不能直接使用 lambda 而不提及它的类型?

c++ - 以类实例为右侧的运算符重载

带有变量的 PHP 模板类?

C++ cin for 循环没有按预期工作?

c++ 类并在其中定义函数?

c++ - 如何将 constexpr 作为模板参数传递?

c++ - 丢弃限定符未知原因 (std::bind()/lambda)

c++ - 使用模板模板参数专门化基类

c++ - 使用非类型模板参数转发声明函数模板