对于课程,是的。对于功能,不,是的。
模板偏特是罚款班,但对全局函数这是一个有点更靠谱。
对于类,你简单地忽略专业化参数从模板参数列表,包括它的类定义:
// General template class for a vector
template <class T, int N>
struct Vector
{
T e[N];
};
// Specialization for N=3
template <class T> // omit the N
struct Vector<T, 3> // and include it here
{
T e[3];
static Vector<T, 3> cross(const Vector<T, 3>& a, const Vector<T, 3>& b)
{
return Vector<T, 3>(a.e[1] * b.e[2] - a.e[2] * b.e[1],
a.e[2] * b.e[0] - a.e[0] * b.e[2],
a.e[0] * b.e[1] - a.e[1] * b.e[0]);
}
};
对于全局的功能,你不能这样做。你可以定义一个完全一般的或完全专用的函数 - 不允许部分函数的特化。
但是,可以部分通过创建它作为一个专门的部分类的静态功能的代理专业化的功能。
例如
template <class A, class B>
void foo(A a, B b)
{
foo_impl::fun(a, b);
}
template <class A, class B>
struct foo_impl
{
static void fun(A a, B b)
{
// real implementation here
}
};
然后,您可以专注于你想要的任何方式foo_impl
,这将在foo
反映。