当模板完全专用时,不需要复制成员函数.例如,在以下代码中,foo()
只写入一次.
#include <iostream>
template<int M>
class B
{
public:
void foo();
private:
void header();
};
template<int M>
void
B<M>::foo()
{
// specialized code:
header();
// generic code:
std::cout << "M = " << M << std::endl;
}
template<int M>
void
B<M>::header()
{
std::cout << "general foo()" << std::endl;
}
template<>
void
B<2>::header()
{
std::cout << "special foo()" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
但是,对于部分特化,有必要复制类定义和所有成员函数.例如:
#include <iostream>
template<int M, int N>
class A
{
public:
void foo();
private:
void header();
};
template<int …
Run Code Online (Sandbox Code Playgroud)