简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM