gcc problem with explicit template instantiation?

2019-05-29 03:38发布

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?

2条回答
【Aperson】
2楼-- · 2019-05-29 04:27

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.

查看更多
虎瘦雄心在
3楼-- · 2019-05-29 04:37

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.

查看更多
登录 后发表回答