模板类外部的长定义的替代项
alternatives to the long definition outside template class
假设我有一个模板类,我想在类外定义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在评论中给出的。
相关文章:
- 具有外部"c"和程序集的未定义函数
- C++编程从外部文本文件定义数组大小
- 良好做法:如何定义用于编译的外部库的路径
- 使用外部定义的模板类型作为模板参数的更通用模板的模板别名
- 模板类外部的长定义的替代项
- 使用带有 CMake 和 Conan 的外部库的未定义引用
- 可视化C++外部定义内联函数
- 具有外部定义的默认特殊成员函数
- C++ 为什么在定义的编译和链接之前引用外部实例的程序
- 删除 PCL 可视化工具中定义的 3D 框外部的点
- 在成员函数外部封闭类的定义中需要默认成员初始值设定项
- 为什么在类外部(但在头文件中)定义的类成员函数必须内联?
- 如何在命名空间中声明外部全局,然后定义它?
- 使用静态变量未解析的外部符号/未定义的引用时出错
- 自定义对象构造函数在循环外部循环
- 我可以有一个从外部不可见但未在标头中定义的静态友元函数吗?
- 创建类时已定义的未解析外部符号
- 定义外部时未解析的外部符号"struct API Api"
- 为将来的'unset'变量定义外部变量是否是一种好的做法?
- 在同一头文件中定义外部变量