typedef和显式实例化之间的代码重复

Code duplication between typedefs and explicit instantiations

本文关键字:代码 之间 实例化 typedef      更新时间:2023-10-16

tree.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;
// ...

tree.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和实现文件中的显式类模板实例化之间存在一些代码重复。是否有一些方法可以消除重复,而不需要像往常一样将"所有内容"放在头文件中?

这是无效的,并且被实现拒绝,因为在详细的类型说明符中使用了typedef名称

template class addition;

以下内容也是无效的,因为标准规定在详细说明的类型说明符中必须包含一个简单的模板id。不过,Comeau在线和GCC都接受这一点。

template class addition::binary_operation;

你可以应用一个变态的变通方法,尽管是完全符合标准的

template<typename T> using alias = T;
template class alias<multiplication>::binary_operation;

至少我在快速浏览规范时不会发现它是无效的。

使用宏。你可以写一个类似的标题

I_HATE_MACROS(binary_operation<std::plus<unsigned>, '+'>, addition)
I_HATE_MACROS(binary_operation<std::multiplies<unsigned>, '*'>, multiplication)

然后你可以做

#define I_HATE_MACROS(a, b) typedef a b;

#define I_HATE_MACROS(a, b) template class a;

然后

#include "DisgustingMacroHackery.h"

我问自己,为什么你真的要写一个.cpp文件,因为你有模板,它们要么全部放在头文件中,要么放在一个seprarate文件中,例如".icc",它保存了cpp文件中的内容。我不确定,但tempalates的定义不应该总是在一个编译单元中。

请参阅->在.CPP文件中存储C++模板函数定义