模板专业化适用于您想要为特定模板参数做一些特别不同的事情。编译器将实例化原始模板中未指定的任何内容。
当您想要特定数据类型的不同行为时,这很有用,但也可用于更复杂的模式匹配,例如更改指针类型或const
类型的行为:
template <typename T>
struct is_pointer { static bool value = false; };
template <typename T>
struct is_pointer<T*> { static bool value = true; };
template <typename T>
struct is_const { static bool value = false; };
template <typename T>
struct is_const<const T> { static bool value = true; };
// later, try this:
assert(is_pointer<int*>::value == true);
assert(is_pointer<int>::value == false);
So, long story short: don't bother specifying your template unless you've got something special to do with a certain parameter, that you can't generalize into the base-template. Template specialization is just a rather hardcore form of pattern-matching which can be used for both good and evil.