Zub*_*tta 4 c++ templates instantiation specialization
我一直在努力理解模板专业化.为什么会产生错误(specialization of 'T foo(T, T) [with T = int]' after instantiation)
template <class T> T foo(T a, T b);
int main()
{
int x=34, y=54;
cout<<foo(x, y);
}
template <class T> T foo(T a, T b)
{
return a+b;
}
template <> int foo<int>(int a, int b)
{
cout<<"int specialization";
}
Run Code Online (Sandbox Code Playgroud)
该标准要求在实例化时必须知道所有模板定义,并且每个翻译单元都看到相同的定义.否则您的程序格式不正确(实际上不需要诊断).
(所以要解决这个问题,只需将所有模板定义放在程序的顶部.)
请记住,模板函数不是函数,只是模板.将它们视为代码生成工具.