我想在類的內部定義一個常量,其中的值是最大可能的int值。事情是這樣的:在常量表達式中使用numeric_limits :: max()
class A
{
...
static const int ERROR_VALUE = std::numeric_limits<int>::max();
...
}
這個聲明失敗,出現以下消息編譯:
numeric.cpp:8: error: 'std::numeric_limits::max()' cannot appear in a constant-expression numeric.cpp:8: error: a function call cannot appear in a constant-expression
我明白爲什麼這是行不通的,但兩件事情看起來怪我:
在我看來,在常量表達式中使用該值是自然的決定。爲什麼語言設計者決定使一個函數成爲一個函數,因此不允許這種用法?
中的規範要求18.2.1是
For all members declared static const in the numeric_limits template, specializations shall define these values in such a way that they are usable as integral constant expressions.
難道這是我應該能夠在我的情況下使用它,沒有它違背了錯誤消息?
謝謝。
可以使用climits http://www.cplusplus.com/reference/clibrary/climits/ – Anycorn 2010-04-29 15:14:55
@aaa:但'climits'對模板不會很好。 – UncleBens 2010-04-29 15:17:04
@不幸的是。原則上可以在模板中定義,有些工作可行。或者boost integer_traits我認爲已經提供了它們:'integer_traits <> :: const_max/const_min' – Anycorn 2010-04-29 15:20:21