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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With