当模板被完全特化时,成员函数就不需要被复制了。例如,在下面的代码中,
注意,
在模板部分特化的上下文中,如何避免这种代码重复呢?
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;
}
然而,对于部分特化,需要复制类定义和所有成员函数。例如:
#include <iostream>
template<int M, int N>
class A
{
public:
void foo();
private:
void header();
};
template<int M, int N>
void
A<M, N>::foo()
{
// specialized code:
header();
// generic code:
std::cout << "M = " << M << ", N = " << N << std::endl;
}
template<int M, int N>
void
A<M, N>::header()
{
std::cout << "general foo()" << std::endl;
}
template<int N>
class A<2, N>
{
public:
void foo();
private:
void header();
};
template<int N>
void
A<2, N>::foo()
{
// specialized code:
header();
// generic code:
std::cout << "M = " << 2 << ", N = " << N << std::endl;
}
template<int N>
void
A<2, N>::header()
{
std::cout << "special foo()" << std::endl;
}
注意,
A<2, N>::foo()
是手动替换了M
为2的A<M, N>::foo()
的副本。在模板部分特化的上下文中,如何避免这种代码重复呢?