Emulating the special properties of sizeof with constexpr

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

    Building upon the quite magical answer from n.m., with just tiny bit of massage, it seems it is possible to have bitsof mimic sizeof.

    #include 
    #include 
    #include 
    
    template 
    struct bits_traits {
      enum { value = sizeof(T) * CHAR_BIT };
    };
    
    struct int_12_bit {
      enum { bits = 12 };
    };
    
    template <>
    struct bits_traits {
      enum { value = int_12_bit::bits };
    };
    
    #define bits_traits_of(k) decltype(bits_traits_of_left+(k)+bits_traits_of_right)
    
    struct bits_traits_of_left_t {
        template 
        bits_traits operator+(const T&);
    } bits_traits_of_left;
    
    struct bits_traits_of_right_t {
        template 
        friend T operator+(const T&, bits_traits_of_right_t);
    
        bits_traits_of_right_t operator+();
    
        template 
        operator T() const;
    
    } bits_traits_of_right;
    
    #define bitsof(x) bits_traits_of(x)::value
    
    int main() {
      using std::size_t;
      size_t a = bitsof(int);
      size_t b = bitsof(int_12_bit);
      std::cout <<"a="<< a <<", b="<< b << std::endl;
    
      int_12_bit x;
      size_t c = bitsof(x);
      std::cout <<"c="<< c << std::endl;
    }
    

    The only thing that I changed, other than adding in definitions for bits_traits, is to redefine bitsof so that it returns the bits_traits::value rather than the bits_traits type.

    $ ./a.out 
    a=32, b=12
    c=12
    

    I'm just writing this up to verify that it can work. All credits should go to n.m.'s answer.

提交回复
热议问题