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

fre*_*low 5 c++ templates typedef code-duplication header-files

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;
// ...
Run Code Online (Sandbox Code Playgroud)

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>, '*'>;
// ...
Run Code Online (Sandbox Code Playgroud)

如您所见,头文件中的typedef与实现文件中的显式类模板实例之间存在一些代码重复.有没有办法摆脱不需要像往常一样在头文件中放置"所有"的重复?

Joh*_*itb 3

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

template class addition;
Run Code Online (Sandbox Code Playgroud)

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

template class addition::binary_operation;
Run Code Online (Sandbox Code Playgroud)

您可以应用变态解决方法,但要完全符合标准

template<typename T> using alias = T;
template class alias<multiplication>::binary_operation;
Run Code Online (Sandbox Code Playgroud)

至少我快速浏览一下规范就发现它不再无效了。