-1

Why will i use explicit instantiation of a function template, for a type? If I do not use explicit instantiation of the function, the template is used to create the necessary function then what is the use of explicit instantiation?

template <class Any>
void Swap (Any &, Any &);
// template prototype

template <> void Swap<job>(job &, job &);
// explicit specialization for job

int main(void)
{

template void Swap<char>(char &, char &); 
// explicit instantiation for char

short a, b;
Swap(a,b);
// implicit template instantiation for short

job n, m;
Swap(n, m);
// use explicit specialization for job

char g, h;
Swap(g, h);
// use explicit template instantiation for char

}

In the above eg. explicit instantiation is done for char type. What is the use of this?? If the compiler can make use of the template to make a fn for char type.

If there are any refrences that can help me clear my concept, pls do include those.

4

1 回答 1

1

模板的定义必须在实例化它的每个翻译单元中可用。通常,这是通过在标题中定义模板来实现的;但在某些情况下,您可能不想这样做——也许您不希望您的客户看到实现的源代码。

相反,您可以在标题中声明模板;然后定义它,并在源文件中显式实例化您需要的所有特化。

于 2013-03-01T13:47:52.710 回答