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的静态成员吗?我试图强制模板类型的特定成员变量是静态的时偶然发现了这一点.
Foo::bar在decltype(Foo::bar)说明符中没有访问成员的权限:它只是询问编译器Foo的成员类型,编译器仅从bar声明中知道的信息.
这与sizeof表达式类似:您可以在sizeof(Foo::bar)没有Foo可用实例的情况下执行,编译器将生成正确的结果.