int main(int argc, char const *argv[])
{
int x = 4;
int y = 2;
const int cell = x/y;
auto a = std::bitset<20>{cell}; //fails
auto b = std::bitset<20>(cell); //works
}
为什么std::bitset
不允许我在这里使用大括号构造,而是使用括号构造?如果cell
是constexpr
,则两者都将编译。
编译错误:
test.cpp:21:29: error: non-constant-expression cannot be narrowed from type 'int' to 'unsigned long long' in initializer list [-Wc++11-narrowing]
auto a = std::bitset<20>{x*y}; //fails
^~~
test.cpp:21:29: note: insert an explicit cast to silence this issue
auto a = std::bitset<20>{x*y}; //fails
^~~
static_cast<unsigned long long>( )
1 error generated.
失败的行使用列表初始化语法:
auto a = std::bitset<20>{cell}; //fails
该语法在C++17标准的11.6.4节中进行了定义。相关部分:
T
类型的对象或引用的列表初始化定义如下:(3.7(否则,如果
T
是类类型,则考虑构造函数。列举了适用的构造函数,并通过过载解析(16.3,16.3.1.7(选择了最佳构造函数。如果需要窄化转换(见下文(来转换任何参数,则程序格式错误窄幅转换是一种隐式转换
(7.4(从整数类型或无范围枚举类型到不能表示原始类型的所有值的整数类型,除非源是一个常量表达式,其值在整数提升后将适合目标类型。
这让我们更好地了解了正在发生的事情:
// Works, no narrowing check, implicit conversion.
std::bitset<20> a(2);
std::bitset<20> b(-1);
std::bitset<20> c(cell);
// Works, 2 can be converted without narrowing
std::bitset<20> d{2};
// Fails, -1 cannot be converted without narrowing
std::bitset<20> e{-1};
// Fails, compiler does not understand cell can be converted without narrowing
std::bitset<20> f{cell};
在您的程序中,编译器无法理解cell
是一个常量表达式。它检查std::bitset
的可用构造函数,并发现它必须从int
转换为unsigned long long
。它认为int
可能是负的,因此我们有一个缩小的转换。
我们可以通过使cell
成为比const
更强的constexpr
来解决这个问题。const
仅表示不应更改该值,constexpr
表示该值在编译时可用:
constexpr int x = 4;
constexpr int y = 2;
constexpr int cell = x / y;
auto a = std::bitset<20>{cell}; // works
您现在可以问为什么列表初始化不允许缩小转换范围。我不能完全回答这个问题。我的理解是,隐性狭窄通常被视为不可取的,因为它可能会产生意想不到的后果,因此被排除在外。