在C ++中是否需要布尔值在true时设置为1位/在false时设置为0位

NoS*_*tAl 3 c++ boolean language-lawyer

我正在考虑通过使用uint32_t和bool [4]的并集对返回4个bool的函数进行微优化,然后执行popcnt指令以查看bool数组中有多少个元素是正确的。

But I do not know if the standard guarantees that bool is represented as number with only 1 bit set when true and 0 bits set when it is false.

If the answer is no then I have a follow up question: if it is not required is it required that representation is constant, e.g. if I have a test that checks that true bool casted to uint_8t is 1(and 0 for false) does that this means that every representation of bools in the program will behave the same.

note: I know that it is not required that bool is 1byte, but I can static_assert on that.

L. *_* F. 9

我正在考虑通过使用uint32_t和bool [4]的并集对返回4个bool的函数进行微优化,然后执行popcnt指令以查看bool数组中有多少个元素是正确的。

这将导致未定义的行为,因为访问联合的不活动成员会违反对象生存期规则。您可能想使用a std::bitset<4>代替-它设计用于这样的用法。

请注意,std::bitset不能直接由几个bools 构造,您可能必须先编写一个unsigned long long。或者,您可以使用如下帮助函数:

template <std::size_t N>
constexpr std::bitset<N> pack_bools(const bool (&arr)[N])
{
    static_assert(N <= std::numeric_limits<unsigned long long>::digits);

    unsigned long long num{0};
    for (std::size_t i = 0; i < N; ++i) {
        if (arr[i])
            num += 1LL << i;
    }
    return std::bitset<N>{num};
}
Run Code Online (Sandbox Code Playgroud)

用法:

pack_bools({true, false, true, false}); // for example
Run Code Online (Sandbox Code Playgroud)

测试

但是我不知道标准是否保证布尔值表示为数字,如果为true,则仅设置1位;如果为false,则设置为0位。

不,没有这样的保证。 [basic.fundamental] / 10

类型bool是一种独特的类型,具有与实现定义的无符号整数类型相同的对象表示,值表示和对齐要求。type的值 booltruefalse。[ 注:有没有signedunsignedshort,或long bool类型或值。— 尾注 ]

关于价值表示不再有任何保证。

如果答案是否定的,那么我会有一个后续问题:如果不需要,是否要求表示形式是恒定的,例如,如果我有一个测试来检查强制转换为uint_8t的true bool为1(对于false,则为0),是否可以做到这一点?这意味着程序中每个布尔变量的表现都将相同。

不,也没有这样的保证。

  • 当涉及到生命周期规则时,@ NoSenseEtAl POD并不是那么重要。是的,有时候我们都认为定义明确的不是:) (2认同)