I'm attempting to create a struct to hold a file header within the declaration section of a class in a header file. This involves calculation of a value that is known at compile time, and I want to use it to size an array within the header.
This is an extract from a header file of what I've most recently been trying:
const uint hFreeSiz = (1024 - sizeof(uint32_t) - sizeof (uint16_t)- sizeof (uint16_t) - sizeof(RId))/sizeof (RId);
template <const uint freedSiz>
struct FBHead
{
/** A magic number for the file. Indicates both class and version. */
uint32_t fSig;
/** The number of data bytes within each block. */
uint16_t blkSize;
/** The number of records available for reuse. */
uint16_t freedCnt;
/** The id number of the last record written to the file. */
RId lstRec;
RId freedRecs[freedSiz];
};
FBHead<hFreeSiz> fbHead;
but it tells me:
error: invalid use of non-static data member 'FBFile::hFreeSiz'
I could calculate this by hand, but I'm trying to understand what's going on here and why this isn't working. Can anyone explain? (I'm guessing that if I moved the constant declaration outside the class, then it would work, but I'd really rather keep it close to the stuff that it's used to modify. In fact, if that's the only answer, then I'll probably calculate it by hand and put in comments about why that particular number.)
CodePudding user response:
The modern way would be to use a constexpr
, to tell the compiler it is an actual compile-time constant. See a simpler example:
constexpr int Size = sizeof(long) * 7;
class Foo
{
int t[Size];
};
or
class Foo
{
static constexpr int Size = sizeof(long) * 7;
int t[Size];
};