![](/img/trans.png)
[英]Why can't I initialize non-const static member or static array in class?
[英]Why can a non-const, non-static member be accessed at compile time without an instance of the class?
以下在VS2017中編譯良好:
#include <type_traits>
struct Foo
{
int bar;
};
int main()
{
static_assert(std::is_same_v<decltype(Foo::bar), int>, "Foo::bar isn't an int");
return 0;
}
Foo :: bar的訪問是否應該在編譯時不強制其為Foo的靜態成員? 我在嘗試強制模板類型的特定成員變量為靜態時偶然發現了這一點。
在decltype(Foo::bar)
說明符中無法訪問成員Foo::bar
:它只是向編譯器詢問Foo
成員的類型,這是編譯器僅從bar
的聲明中知道的信息。
這類似於sizeof
表達式:您可以在沒有可用Foo
實例的情況下執行sizeof(Foo::bar)
,編譯器將產生正確的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.