delphifirst
delphifirst

Reputation: 1847

When will implicit instantiation cause problems?

I'm reading C++ Primer, and it says:

"If a member function isn't used, it is not instantiated. The fact that members are instantiated only if we use them lets us instantiate a class with a type that may not meet the requirements for some of the template’s operations."

I don't know why this is a problem. If some operations are required, why doesn't compiler instantiate those operations? Can someone give an example?

Upvotes: 0

Views: 159

Answers (1)

Potatoswatter
Potatoswatter

Reputation: 137770

That's an ease-of-use feature, not a pitfall.

Lazy instantiation serves to simplify templates. You can implement the set of all possible member functions that any specialization might have, even if some of the functions don't work for some specializations.

It also reduces compile time, since the compiler never needs to instantiate what you don't use.

To prevent lazy instantiation, use explicit instantiation:

template class my_template< some_arg >;

This will immediately instantiate all the members of the class (except members which are templates, inherited, or not yet defined). For templates that are slow to compile, you can do the above in one source file (translation unit) and then use the linker to bypass instantiation in other source files, by putting a declaration in the header:

extern template class my_template< some_arg >;

Upvotes: 2

Related Questions