假設在您無法控制的頭檔案中有一個宣告,該宣告如下:
static const uint16 MaxValue = 0xffff; // the type could be anything, static or not
在包含上述內容的檔案中,您有如下代碼:
int some_function(uint16 n) {
if (n > MaxValue) {
n = MaxValue;
}
do_something(n);
...
}
編譯器會警告 if 陳述句始終為 false,因為n不能大于 0xffff。
一種方法可能是洗掉代碼。但是,如果稍后有人想將 的值更改為MaxValue較低的值,那么您剛剛引入了一個錯誤。
兩個問題:
- 是否有任何 C 模板或技術可用于確保代碼在不需要時(因為
MaxValue是 0xfff)被洗掉并被包含(當MaxValue不是 0xffff 時)? - 假設您想顯式地撰寫一個額外的檢查以查看是否
MaxValue等于該型別可以容納的限制,是否有一種可移植的技術可用于識別MaxValue如果稍后MaxValue更改的代碼將起作用的型別的最大值?- 含義:如何通過變數名推斷型別的最大值?
- 我寧愿不使用
limits.h或<limit>常量USHRT_MAX,或未std::numeric_limits<uint16>明確使用的事件。 - 可以使用類似的東西
std:numeric_limits<MaxValue>嗎?
- 我寧愿不使用
- 含義:如何通過變數名推斷型別的最大值?
uj5u.com熱心網友回復:
typeid 導致 type_info const & 而不是變數的型別,使用
std::numeric_limits<decltype(variable)>::max()
反而。
uj5u.com熱心網友回復:
嘗試這個:
std:numeric_limits<decltype(n)>::max()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/364603.html
上一篇:使用C 模板進行除錯
