Sunday, 15 April 2012

c++ - How to get smallest variable with C++11 user defined literals -


I am looking at some new features of C ++ 11 and are very impressed with some of them, especially user defined Verbatim

This allows you to define the written words of 999_something , where to generate some control 999 For now, it is not being used:

  #define MEG * 1024 * 1024 int ten_meg = 10 m;   

I was thinking that it would be good to apply a large number of underscores, such as 1_000_000_blah which would conform to Pearl's readability, although this idea is somewhat readable I feel quite humorous: -)

This will also be easy for binary values ​​like 1101_1110_b and 0011_0011_1100_1111_b .

Obviously due to the _ characters, they will need the raw mode type, the string must be processed, and I am fine with it.

I can not find out how to distribute a different type depending on operand size, for example:

  1101_1110_b   

should be given a char (value is char) is 8-bit unless:

  0011_0011_1100_1111_b   

will deliver a 16-bit type.

I can get the length of the operation from the literal operator function operator "" Only (by counting the numbers of digits), but return Raksha Function is being fixed, so I can not return a different type on it.

Is it a suffix _b within the defined type of user , Or I need to manually support a different type of partition ( _b8 , _b16 and so on) and provide more duplicate functions ?

You should know Oh, your string size, and the only way to achieve this is that sizeof ... . You should be able to get what you want with a variadic template operator ":

  #include & lt; cstdint & gt; # Include & Lt; type_traits & gt; template & lt; char ... string & gt; auto operator "" _b () - & gt; Typename std :: conditional & lt; sizeof ... (string) & lt; = 8, Uint8_t, typename std :: conditional & lt; sizeof ... (string) & lt; = 16, uint16_t, uint32_t & gt; :: Type & gt; ::   

and here There is a test case:

  int main () {auto a = 10000001_b; auto B = 100000001_b; std :: cout  std :: conditional  machinery is quite ugly You probably can do some work with  boost :: mpl :: vector ,  boost :: mpl :: at  and some arithmetic operations.   

No comments:

Post a Comment