簡體   English   中英

為什么在沒有類實例的情況下可以在編譯時訪問非常量,非靜態成員?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM