std :: bitset有constexpr构造函数和constexpr运算符[],因此以下代码成功编译:
#include <bitset>
typedef std::bitset<5> BitSet;
constexpr BitSet s1;
static_assert(!s1[0]);
为什么以下代码没有?
static_assert(BitSet{}[0]);
当您编写BitSet{}
时,会创建一个类型为BitSet
的临时对象。但std::bitset
的非const对象的operator[]
不是constexpr!
在你的第一个例子中,s1
是隐含的const
,所以它使用const operator[]
,即constexpr
。
既然你不能const
直接限定临时(如const Foo()
无效),你可以随时添加const
到你的别名:
using BitSet = const std::bitset<5>;