模板类外部的长定义的替代项

alternatives to the long definition outside template class

本文关键字:定义 外部      更新时间:2023-10-16

假设我有一个模板类,我想在类外定义operator=

template<uint32_t total_count, uint32_t init_count, uint32_t node_count>
class cls
{
...
cls & operator= (cls && c);
...
};
template<uint32_t total_count, uint32_t init_count, uint32_t node_count>
cls<total_count, init_count, node_count> & 
cls<total_count, init_count, node_count>::operator= 
(cls<total_count, init_count, node_count> && c)
{
...
}

除了缩短模板参数名称之外,是否有上述定义的替代方案?

您的定义版本确实比必要更频繁地重复模板参数。函数的限定名告诉编译器上下文是具有指定模板参数的cls类模板。在此之后,可以假定出现的任何cls(不带参数(都表示此上下文,类似于您在模板定义中执行的操作。所以参数列表中的显式模板参数不是必需的;一个简单的cls可以假设意味着cls<total_count, init_count, node_count>.

语法技巧同样可以简化返回类型。C++11 中引入的尾随返回类型允许在函数名称引入上下文之后声明返回类型。与参数列表一样,一旦您进入正确的上下文,就可以省略模板参数。

template<uint32_t total_count, uint32_t init_count, uint32_t node_count>
auto cls<total_count, init_count, node_count>::operator= (cls && c) -> cls & 
{
...
}

社区维基,因为这些简化是由POW和parktomatomi在评论中给出的。