为什么模板专业化中的显式实例化会给我带来错误

Why explicit instantiation in template specialization is giving me error?

本文关键字:错误 实例化 专业化 为什么      更新时间:2023-10-16

考虑代码:

...
template <typename T>
void Swap(T &,T &);
template <> void Swap<structEmployee>(structEmployee &,structEmployee &);
int main()
{
template void Swap<char>(char &,char &);
short a=10,b=20;
...
Swap(a,b);
...
...
}

它给了我一个错误:

expected primary-expression before ‘template’
 template void Swap<char>(char &, char &);

您不能在块范围内实例化模板,它必须在全局范围内:

//Instantiation in global scope
template void Swap<char>(char &,char &);
int main()
//...