【发布时间】:2012-07-10 13:50:53
【问题描述】:
树.h
template<typename Functor, char Operator>
class binary_operation : public node
{
// ... unimportant details ...
unsigned evaluate() const;
void print(std::ostream& os) const;
};
typedef binary_operation<std::plus<unsigned>, '+'> addition;
typedef binary_operation<std::multiplies<unsigned>, '*'> multiplication;
// ...
树.cpp
template<typename Functor, char Operator>
unsigned binary_operation<Functor, Operator>::evaluate() const
{
// ... unimportant details ...
}
template<typename Functor, char Operator>
void binary_operation<Functor, Operator>::print(std::ostream& os) const
{
// ... unimportant details ...
}
template class binary_operation<std::plus<unsigned>, '+'>;
template class binary_operation<std::multiplies<unsigned>, '*'>;
// ...
如您所见,头文件中的 typedef 与实现文件中的显式类模板实例化之间存在一些代码重复。有什么方法可以摆脱不需要像往常一样将“所有内容”放在头文件中的重复项?
【问题讨论】:
-
我认为你不能在 .cpp 文件中写
template class addition;,这是一种耻辱。 -
不 :(
error: using typedef-name 'addition' after 'class' -
我认为 decltype 也无济于事......但 C++ 仍然有旧的预处理器......你可以用公共部分制作一个宏 :-)
-
您可以添加第二个头文件,并将代码放在那里。没有多大帮助,但它会防止你的原始 .h...
标签: c++ templates typedef header-files code-duplication