typedef模板,这可能吗

typedef template, is this one possible?

本文关键字:模板 typedef      更新时间:2023-10-16

是否可以执行以下操作:

template< typename T >
using T_CCUnit = static const constexpr T;

事实上,我只是想要一个static const constexpr的别名,因为每次在某个文件中写都很无聊。我更喜欢c++11中的解决方案。

您可以很容易地为类型添加常量,因为cv限定符会修改类型:

template <typename T>
using T_C = std::add_const_t<T>;

但是,staticconstexpr修改声明,而不是类型。所以,这里:

                         int x1;
                   const int x2;
  static           const int x3;
  static constexpr const int x4;
//      |    ^    |  type   |name
//   ^  | constexpr specifier
// storage class specifier

最后三个声明都属于const int类型,但x2x3x4具有不同的存储类。

老实说,如果主要问题是

写作真的很无聊。。。

我最好的建议是,你应该学习如何在你喜欢的编辑器中编写宏或保存常见的代码片段。

我认为对您来说最好的解决方案是使用宏。

#define STATIC_CONST_CONSTEXPR static const constexpr

但说真的,staticconstexpr并不是该类型的修饰符。在您的情况下,使用using所能做的就是const T。其他的一切你要么自己写,要么请预处理器为你写。

static存储限定符适用于实例,而不是类型。所以typedef是不可能的。

您不能typedef staticconstexpr,它们都不是类型的一部分。也就是说,即使你可以,也没有人会知道什么:

T_CCUnit<int> x = 4;

意思是,但每个人都会知道什么:

static constexpr int x = 4;

手段。每次额外键入7个字符以使代码更加易读是值得的。所有阅读您代码的人,以及您未来的自己,都会感谢您。


附带说明,constconstexpr是冗余的——声明的constexpr的每个变量都隐式地为const