问题
I often have the situation where I need several constants generated at compile time for the use of bit shift and masking operations.
e.g.
#define blockbits 8
#define blocksize 256 // could be generated from 2^blockbits
#define blocksize 0xFF // could be generated from blocksize - 1
I would like all these to be generated from blockbits
, however there is no power operation that can be used in the preprocessor that I am aware of.
Does anyone know a simple way of generating this sort of thing at compile time?
回答1:
You can define them as mathematical expressions:
#define blockbits 8
#define blocksize (1 << blockbits)
#define blockXXXX (blocksize - 1) // changed from blocksize to blockXXXX, since blocksize is already taken
The parentheses are to make sure there are no operator precedence issues when you use them in other expressions.
You also might want to change the names to all uppercase like BLOCKBITS
, BLOCKSIZE
, etc, which is a C++ naming convention to distinguish macros from normal names.
回答2:
If you want to use const's instead of #define's and if you want to make a generic power function (not just for powers of 2) that will calculate values at runtime, you could also try doing it with templates like this:
template<int num, int pow> struct temp_pow
{
static const unsigned int result=temp_pow<num, pow-1>::result*num;
};
template<int num> struct temp_pow<num, 1>
{
static const unsigned int result=num;
};
const int BLOCKBITS = 8;
const int BLOCKSIZE = temp_pow<2,BLOCKBITS>::result; // could be generated from 2^BLOCKBITS
const int BLOCKSIZE_1 = BLOCKSIZE-1;
来源:https://stackoverflow.com/questions/13317401/mathematical-operations-during-compiler-preprocessing