Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template specialization with empty brackets and struct

I am used to the template syntax of the form struct hash<template class Key> but what is the difference when using template <> struct hash<Key> ?

namespace std {

  template <>
  struct hash<Key>
  {
    std::size_t operator()(const Key& k) const
    {
      ....
    }
  };
}

Please note that I did search for the meaning of template <> and I understand (I hope) that it's a way, when using pattern matching to specify the non-matched case, but together with the usage of struct<Key> I do not understand the motivation of it.

like image 383
user695652 Avatar asked Jul 19 '16 19:07

user695652


1 Answers

There are different levels of template specialization:

1) Template declaration (no specialization)

template <class Key, class Value>
struct Foo {};

2) Partial specialization

template <class Key>
struct Foo<Key, int> {};

3) Full/explicit specialization

template <>
struct Foo<std::string, int> {};

Then, when instantiating the templates, the compiler will choose the most specialized definition available:

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 and #3 work for template functions as well.

like image 173
0x5453 Avatar answered Dec 12 '22 05:12

0x5453