在 c++ 11 中。
实例化:
用给定的模板参数实例化模板
template <typename T>
struct test{ T m; };
template test<int>;//explicit instantiation
这会导致定义一个标识符为test<int>的结构体
test<int> a;//implicit instantiation
如果template <typename T> struct test 之前已经用参数T = int 实例化(显式或隐式),那么它只是一个结构实例化。否则,它会先隐式实例化template <typename T> struct test 参数T = int,然后实例化结构test<int> 的实例
专业化:
特化是仍然是模板,您仍然需要实例化才能获得真正的代码。
template <typename T>
struct test{ T m; };
template <> struct test<int>{ int newM; } //specialization
模板专业化最有用的可能是您可以为不同的模板参数创建不同的模板,这意味着您可以为不同的模板参数定义不同的类或函数。
template<> struct test<char>{ int cm; }//specialization for char
test<char> a;
a.cm = 1;
template<> struct test<long> { int lm; }//specialization for long
test<long> a;
a.lm = 1;
除了上面的这些完整模板特化之外,还有(仅类模板)退出部分模板特化。
template<typename T>
struct test {};
template <typename T> struct test<const T>{};//partial specialization for const T
template <typename A, typename B>
struct test {};
template <typename B> struct test<int, B>{};//partial specialization for A = int