Emulating the special properties of sizeof with constexpr

后端 未结 4 1393
春和景丽
春和景丽 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 22:01

    You can do something like this:

    #include 
    
    #define bitsof(k) decltype(bitsof_left+(k)+bitsof_right)
    
    template 
    struct bits_traits { /* whatever you want here */ };
    
    struct bitsof_left_t {
        template 
        bits_traits operator+(const T&);
    } bitsof_left;
    
    struct bitsof_right_t {
        template 
        friend T operator+(const T&, bitsof_right_t);
    
        bitsof_right_t operator+();
    
        template 
        operator T() const;
    
    } bitsof_right;
    
    int main()
    {
        using foo = bitsof(42);
        using bar = bitsof(int);
    
        static_assert(std::is_same>::value);
        static_assert(std::is_same>::value);
    }
    

    It works like this.

    a + (42) + b is parsed as (a + (42)) + b), then overloaded binary operator+ at either side kicks in. In my example the operators are only declared, not defined, but since it's unevaluated context, it doesn't matter.

    a + (int) + b is parsed as a + ((int) (+ b)). Here we employ the overloaded unary + at the right side, then overloaded cast operator, then overloaded binary + at the left side.

提交回复
热议问题