Albert
Albert

Reputation: 1113

Instantiation of template

If I have the following code:

template <typename T = int>
struct mystruct {
  using doublestruct = mystruct<double>;
}

mystruct<>::doublestruct obj;

Does this instantiate the mystruct<int> template at all? Or only the mystruct<double> is instantiated?

Upvotes: 24

Views: 581

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254431

Yes, it will have to instantiate mystruct<int> in order to access its members and determine the meaning of doublestruct. You could test this with a static_assert:

#include <type_traits>

template <typename T = int>
struct mystruct {
  static_assert(!std::is_same<T,int>::value, "");
  using doublestruct = mystruct<double>;
};

mystruct<>::doublestruct obj;     // assertion fails for T==int
mystruct<char>::doublestruct obj; // OK, not instantiated for int

Upvotes: 18

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385088

Yes, it must be instantiated; doublestruct is a member of the instantiation so, if you do not have an instantiation, you do not have a doublestruct.

[C++11: 14.7.1]: Unless a class template specialization has been explicitly instantiated (14.7.2) or explicitly specialized (14.7.3), the class template specialization is implicitly instantiated when the specialization is referenced in a context that requires a completely-defined object type or when the completeness of the class type affects the semantics of the program. [..]

In particular, consider the potential effect of specialisations of mystruct that may not contain a member doublestruct, or may contain one that is not a type.

Upvotes: 16

Related Questions