TheYokai
TheYokai

Reputation: 351

Compile-time Type Replacement in C++

Say I have a program that uses a built in type such as float and I want to have the ability to supply a command-line argument to my compiler to change all float declarations to be fixed_point<8,8> instead.

Presuming that they're the exact same interface (as in, they can be treated the same with regards to assignment / addition / conversion / etc), is there a way in via compiler or build system (cmake / scons / etc) to swap types during compilation when specifying a specific flag? This would serve a few benefits with regards to determinism, for instance.

Upvotes: 1

Views: 203

Answers (1)

Mansoor
Mansoor

Reputation: 2438

You can declare your variable with an alias type, which is defined conditionally based on a preprocessor definition, like this:

#ifdef LARGEFLOATS
using MYFLOAT = long double;
#else
using MYFLOAT = double;
#endif

You can then use the -D compiler flag to set the preprocessor definition, e.g. -DLARGEFLOATS (for MSVC, the syntax is /D). Need to be careful that all translation units see the same preprocessor definition. In my example, this could lead to a narrowing conversion.

Upvotes: 6

Related Questions