为什么在没有类实例的情况下可以在编译时访问非const,非静态成员?

Hat*_*ead 1 c++ static templates compile-time

以下编译在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;
}
Run Code Online (Sandbox Code Playgroud)

如果Foo :: bar的访问在编译时没有强制它是Foo的静态成员吗​​?我试图强制模板类型的特定成员变量是静态的时偶然发现了这一点.

das*_*ght 5

Foo::bardecltype(Foo::bar)说明符中没有访问成员的权限:它只是询问编译器Foo的成员类型,编译器仅从bar声明中知道的信息.

这与sizeof表达式类似:您可以在sizeof(Foo::bar)没有Foo可用实例的情况下执行,编译器将生成正确的结果.