为什么可以在没有 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),编译器将生成正确的结果。