为什么必须在使用模板的每个函数之前声明模板?

Kvo*_*the 2 c++ templates

为什么以下代码有效

template<class T>
T AddThree(T input)
{
    return input + 3;
}

template<class T>    // If I remove this line it won't compile
T SubtractThree(T input)
{
    return input - 3;
}
Run Code Online (Sandbox Code Playgroud)

但如果我注释掉该行表明它不会编译?为什么编译器template<class T>从第一次声明时就不知道(就像在文件正文中声明的其他内容一样)?

Mag*_*off 5

您可以将其视为功能签名的一部分.如果你在一行上写完整的声明,也许更容易看到连接:

template<class T> T AddThree(T input)
{
    return input + 3;
}
Run Code Online (Sandbox Code Playgroud)

这就像你需要为每个函数声明参数一样.你不会期望这个工作:

std::string AddThree(std::string input)
{
    return input + "3";
}

std::string SomethingElse(input)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这里,与模板参数一样,您需要input在第二个函数和第一个函数中声明.这是语言的范围规则:)