Here is my problem. I have a BINARY_FLAG macro:
#define BINARY_FLAG( n ) ( static_cast<DWORD>( 1 << ( n ) ) )
Which can be used either like this ("persistent" script):
static const SomeConstant = BINARY_FLAG( 5 );
or something like this (script "variable"):
for( int i = 0; i < 10; i++ ) { DWORD flag = BINARY_FLAG( i );
This macro is not absolutely reliable - you can go -1 or 34 there, and there will be the biggest warning, but the behavior will be undefined. I would like to make it more reliable.
For a constant scenario, I could use a template:
template<int Shift> class BinaryFlag { staticAssert( 0 <= Shift && Shift < sizeof( DWORD) * CHAR_BIT ); public: static const DWORD FlagValue = static_cast<DWORD>( 1 << Shift ); }; #define BINARY_FLAG( n ) CBinaryFlag<n>::FlagValue
but this will not mean the script "variable" - I will need a runtime statement:
inline DWORD ProduceBinaryFlag( int shift ) { assert( 0 <= shift && shift < sizeof( DWORD) * CHAR_BIT ); return static_cast<DWORD>( 1 << shift ); } #define BINARY_FLAG( n ) ProduceBinaryFlag(n)
The latter is good, but has no compile-time checks. Of course, I would like to check the compilation time, when possible, and check the runtime. In any case, I want as little overhead as possible at runtime, so I donβt want the function call (maybe not inline) when compile time checking is possible.
I saw this question , but it does not seem to be the same issue.
Is there any construction that would allow alternating between them depending on whether the expression passed as the number of flags is a compile-time constant or a variable?
c ++ macros visual-c ++ templates metaprogramming
sharptooth
source share