c++ - C++11 user-defined literals -


this question has answer here:

i'm learning c++11, , interested in user-defined literals. decided play bit it. languages have syntax this:

int n = 1000_000_000; 

i tried simulate feature in c++11.

inline constexpr unsigned long long operator "" _000 (unsigned long long n)noexcept {       return n * 1000; }  inline constexpr unsigned long long operator "" _000_000 (unsigned long long n)noexcept {       return n * 1000*1000; }  inline constexpr unsigned long long operator "" _000_000_000 (unsigned long long n)noexcept {       return n * 1000*1000*1000; }  int main(){      constexpr auto = 100_000; // instead of 100000      constexpr auto j = 23_000_000; // instead of 23000000; } 

but general case couldn't simulate it, i.e.

auto general_case = 123_456_789; //can't compile

my question "can simulate general case above using c++11?".

this not possible user defined literals in c++11 version of language right now. user defined literals support limited format parameters, doesn't seem support right side parameter, chaining, plus there problem of representing numbers begin 0 actual numbers. no go.

you current approach defines _000 , on standalone literals, compiler work them , no other. not _ operator , 000 parameter can work unfortunately.

you use letter suffixes instead.

long long constexpr operator"" k (long double n) {     return n * 1000; } long long constexpr operator"" m (long double n) {     return n * 1000000; } long long constexpr operator"" g (long double n) {     return n * 1000000000; } 

and then:

0.05m == 50000; 123.232k == 123232 1.000000001g == 1000000001 

surely, last case sort of defeats purpose, because once again have many zeroes without visual indication... can go like:

1.g + 1 == 1000000001 // clearer 1 billion + 1 

this makes little ugly, since literal expects real number , won't work integer unless define literal use integers. can use 1g instead.

also, approach produce compiler warnings, apparently c++ group wants reserve suffixes not preceded underscore "future uses". if want warnings gone, use _k _m , _g instead.

edit: removed initializer list solution, because produces invalid results numbers 010, processed octal , mess calculations.


Comments

Popular posts from this blog

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -

java - JavaFX 2 slider labelFormatter not being used -