简体   繁体   中英

Accepting u in floating point numbers

I have a set of c++ files which are autogenerated by a tool which we cant change . These file are compiled at run time based on user inputs . These files have `double f = userInputs ; definitions. userInputs is provide by users who might provide an input of say 25u . so autogenerated file will have double f = 25u written in them . Now I wish that in userInputs u get replaces with *1.06-6 in the code . But this is autogenerated and not in my control .

All the autogenerated code uses a file stdAfx.h which is under my control . Can i do #define or typedef ec in this file so that the autogenerated file with double f = userInputs gets compiled right even if user says 25u ?

You could do #define double DoubleWrapper . DoubleWrapper would have a constructor taking an unsigned int , storing it internally as a double multiplied by the number you want. You probably want to add a plain double constructor too.

You should also add a cast operator to double , which would return it's internally stored variable.

This way your replaced double works like a double everywhere unless:

  • you provide it an unsigned int
  • you used it as another type without explicitly casting it, because C++ won't chain multiple implicit casts

Depending how your project is structured, this might be acceptable, or might be too much restriction.

Also note that:

  • this is nonstandard, you shouldn't redefine keywords. But every compiler allows it
  • it might cause hard to understand problem if this stdAfx.h is used by other parts of your project, as it changes how double behaves with generally. Since that's probably a precompiled header used by every of your files, you shouldn't do it like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM