When a template is fully specialized, a member function does not need to be duplicated. For example, in the following code, foo()
is written only once.
#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;
}
However, for partial specialization, it is necessary to duplicate the class definition and all member functions. For example:
#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;
}
Notice that A<2, N>::foo()
a duplicate of A<M, N>::foo()
with 2 manually substituted for M
.
How can such code duplication be avoided in this context of template partial specialization?