Emulating the special properties of sizeof with constexpr

后端 未结 4 1387
春和景丽
春和景丽 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:53

    Its hard and probably impossible, mainly because you can only pass compile-time constants as template values to templates, hence your last example with the int_12_bit x; will never be able to be a template value (and types can't be passed as parameters, of course). I played around a bit with decltype, declval and different templates, but I simply could not get it to take in types and (non-constand expression) values with a single "call". It's really unfortunate decltype doesn't accept types, I wonder why the committee choose to only accept expressions.

    Since you mentioned gcc-extensions, there is an extension which can make it work, __typeof__.

    I personally have never used this extension, but it seems like it works similar to decltype but it also accepts types directly.

    This snipped compiles under gcc x86-64 8.3 for me:

    template
    struct bits_trait;
    
    template<>
    struct bits_trait{};
    
    void f() {
        int x;
        bits_trait<__typeof__(x)>();
        bits_trait<__typeof__(int)>();
    }
    

    But this will only compile under gcc.

    Edit: Clang seems to support it as well, no luck with MSVC though.

提交回复
热议问题