【发布时间】:2016-01-25 17:21:37
【问题描述】:
当模板完全特化时,不需要复制成员函数。例如,在下面的代码中,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() 与 A<M, N>::foo() 重复,其中 2 手动替换了 M。
在模板偏特化的情况下,如何避免重复代码?
【问题讨论】:
-
我不知道你可以在不专门化整个类的情况下为类模板专门化一个方法。
标签: c++ templates partial-specialization