我正在嘗試創建一個結構來保存頭檔案中類的宣告部分中的檔案頭。這涉及計算編譯時已知的值,我想用它來確定標頭中陣列的大小。
這是我最近嘗試的頭檔案的摘錄:
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;
但它告訴我:
錯誤:非靜態資料成員 'FBFile::hFreeSiz' 的無效使用
我可以手動計算這個,但我試圖了解這里發生了什么以及為什么這不起作用。誰能解釋一下?(我猜如果我將常量宣告移到類之外,那么它會起作用,但我真的寧愿讓它靠近它用來修改的東西。事實上,如果這是唯一的答案,那么我' 可能會手工計算它并評論為什么這個特定的數字。)
uj5u.com熱心網友回復:
現代方法是使用constexpr, 告訴編譯器它是一個實際的編譯時常量。看一個更簡單的例子:
constexpr int Size = sizeof(long) * 7;
class Foo
{
int t[Size];
};
或者
class Foo
{
static constexpr int Size = sizeof(long) * 7;
int t[Size];
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/376782.html
上一篇:查找陣列中最大數字的索引
