gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:50:36 24 4
gpt4 key购买 nike

为什么下面的代码有效

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;
}

但是如果我注释掉指示它不会编译的行?为什么编译器仍然不知道 template<class T>从第一次声明开始(就像文件正文中声明的任何其他内容一样)?

最佳答案

您可以将其视为函数签名的一部分。如果将完整的声明写在一行中,可能会更容易看出其中的联系:

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

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

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

std::string SomethingElse(input)
{
// ...
}

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

关于c++ - 为什么必须在每个使用模板的函数之前声明模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28681893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com