typedefs和显式实例化之间的代码重复 [英] Code duplication between typedefs and explicit instantiations

查看:145
本文介绍了typedefs和显式实例化之间的代码重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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和在实现文件中的显式类模板实例化。有没有一些方法来摆脱重复,不需要像往常一样把头文件中的一切?

As you can see, there is some code duplication between the typedefs in the header file and the explicit class template instantiations in the implementation file. Is there some way to get rid of the duplication that does not require putting "everything" in the header file as usual?

推荐答案

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

This is invalid and rejected by implementations because a typedef name is used in the elaborated type specifier

template class addition;

以下内容也无效,因为标准表示必须有一个简单的模板标识详细说明类型说明符。 Comeau在线和GCC都接受它,虽然。

The following is invalid too, because the Standard says that there must be a simple template id contained in the elaborated type specifier. Comeau online and GCC both accept it, though.

template class addition::binary_operation;

您可以应用一个变通的解决方法,但完全符合标准

You could apply a pervert workaround though to be fully Standards compliant

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

至少我在快速浏览规格时发现它无效了。

At least I could not find it being invalid anymore on a quick glance over the spec.

这篇关于typedefs和显式实例化之间的代码重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆