这个关于类模板中静态信息的编译器错误意味着什么

What does this compiler error regarding statics in a class template mean?

本文关键字:编译器 错误 意味着 什么 信息 静态 于类模      更新时间:2023-10-16

我在玩类模板和静态,看到了这个:

template<int I>
struct rat
{
    static bool k;
};
bool rat<3>::k = 0; //this is line 84 of the only source file play.cpp
int main(int argc, char **argv)
{
    rat<3> r;
}

编译器错误:play.cpp:84:错误:模板参数列表太少

当我说rat<3> ::k我正在实例化该模板并为该特定模板定义静态,因此从那时起rat<3>的使用就可以了。为什么这不起作用?

应该是

template<>
bool rat<3>::k = 0;

但最好使用false代替bool而不是0,因为它更可读

此外,如果您想将所有模板的变量初始化为true,例如:

template<int I>
bool rat<I>::k = true;

您仍然可以为I = 3:专门化模板

template<>
bool rat<3>::k = false;

您忘记了模板:

template<>
bool rat<3>::k = 0;

当然MSVS接受您的语法(但如果我关闭语言扩展,就不会接受)。