Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiation of template

Tags:

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?

like image 509
Albert Avatar asked Apr 17 '15 11:04

Albert


People also ask

What is instantiation of a template?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation. The definition created from a template instantiation to handle a specific set of template arguments is called a specialization.

How do I instantiate a template class?

To explicitly instantiate a template class function member, follow the template keyword by a declaration (not definition) for the function, with the function identifier qualified by the template class, followed by the template arguments.

Why we need to instantiate the template?

In order for any code to appear, a template must be instantiated: the template arguments must be provided so that the compiler can generate an actual class (or function, from a function template).

What is implicit instantiation?

Implicit instantiation means that the compiler automatically generates the concrete function or class for the provided template arguments. In general, the compiler also deduces the template arguments from the function's arguments. In C++17, the compiler can also deduce the template arguments for class templates.


1 Answers

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 
like image 179
Mike Seymour Avatar answered Nov 01 '22 17:11

Mike Seymour