How do I check if a template parameter is a power of two?

后端 未结 3 917
刺人心
刺人心 2021-02-05 10:47

I want to create a structure that allocates statically an array of 2^N bytes, but I don\'t want the users of this structure to specify this size as the exponent

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-05 11:31

    These days, with constexpr and the bit twiddling hacks you can just

    constexpr bool is_powerof2(int v) {
        return v && ((v & (v - 1)) == 0);
    }
    

提交回复
热议问题