使用空括号和结构的模板专业化

use*_*652 9 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
    {
      ....
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

请注意,我确实搜索了它的含义,template <>并且我理解(我希望)这是一种方式,当使用模式匹配来指定不匹配的情况时,但是与struct<Key>我的使用一起不理解它的动机.

0x5*_*453 23

模板专业化有不同级别:

1)模板声明(无专业化)

template <class Key, class Value>
struct Foo {};
Run Code Online (Sandbox Code Playgroud)

2)部分专业化

template <class Key>
struct Foo<Key, int> {};
Run Code Online (Sandbox Code Playgroud)

3)完全/明确的专业化

template <>
struct Foo<std::string, int> {};
Run Code Online (Sandbox Code Playgroud)

然后,在实例化模板时,编译器将选择最专业的定义:

Foo<std::string, std::string> f1; // Should match #1
Foo<int,         int>         f2; // Should match #2
Foo<std::string, int>         f3; // Should match #3
Run Code Online (Sandbox Code Playgroud)

#1和#3也适用于模板功能.