Emulating the special properties of sizeof with constexpr

后端 未结 4 1397
春和景丽
春和景丽 2021-02-10 21:20

In C++ sizeof is somewhat unique in that it\'s legal to write this:

int x;
sizeof(x); // a variable

As well as simply:

<         


        
4条回答
  •  花落未央
    2021-02-10 21:50

    Not considering macros and without decltype, it is simply not possible because of the language syntax.

    However you can get pretty damn close:

    template 
    constexpr auto bitsof(T) { return sizeof(T) * CHAR_BIT; }
    
    template <>
    constexpr auto bitsof(int_12_bit) { return 12; }
    
    template 
    constexpr auto bitsof() { return sizeof(T) * CHAR_BIT; }
    
    template <>
    constexpr auto bitsof() { return 12; }
    
    auto test()
    {
        constexpr int a{};
        constexpr int_12_bit x{};
    
        static_assert(bitsof(a) == 32);
        static_assert(bitsof(x) == 12);
    
        static_assert(bitsof() == 32);
        static_assert(bitsof() == 12);
    }
    

    Aside from the slightly different syntax (but c'mon it's so close it shouldn't really matter) the biggest difference to the sizeof is that the arguments are not in an unevaluated context. So bitsof(foo()) will call foo(). And bitsof(a) is UB if a is uninitialized.

提交回复
热议问题