gcc problem with explicit template instantiation?

戏子无情 提交于 2019-12-08 03:22:34

问题


It is my understanding that either a declaration or typedef of a specialization ought to cause a template class to be instantiated, but this does not appear to be happening with gcc. E.g. I have a template class, template class Foo {};

I write

  class Foo<double>;  

or

typedef Foo<double> DoubleFoo;  

but after compilation the symbol table of the resulting object file does not contain the members of Foo.

If I create an instance:

Foo<double> aFoo;  

then of course the symbols are all generated.

Has anyone else experienced this and/or have an explanation?


回答1:


The syntax for explicit instantiation is

template class Foo<double>;

See C++03 §14.7.2.

Hoping the functions get generated and linked, but not stripped after creating, but not using, an instance (the most minimal implicit instantiation), is quite a gamble.




回答2:


You are talking about implicit instantiation. But that does only happen if the completenes of the class type would affect semantics of the program.

In your case, the class type doesn't need to be complete because the type you typedef can stay incomplete (class body is not needed, so there is no need to instantiate it). To illustrate, you can also say typedef class MyFunnyThing type; in a statement of its own, without ever defining that class anywhere.

If you create an object, the type of it has to be complete, and so the class template then is implicitly instantiated. Please note that implicit instantiation of a class template will not implicitly instantiate the member function or static datamember definitions, unless they are explicitly used elsewhere.

Also, to declare a specialization of a class-template, the whole point is to prevent an instantiation to happen, to tell the compiler "don't instantiate, because later i specialize it explicitly". The declaration if your specialization also misses a template<> in front of it.



来源:https://stackoverflow.com/questions/2738760/gcc-problem-with-explicit-template-instantiation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!