Do typedef and using cause a template instantiation?
Asked Answered
M

1

7

Say I have a template class defined like this

template <typename T>
class Temp{
    // irrelevant
};

I can either implicitly or explicitly instantiate it:

Temp<int> ti;
template class Temp<char>;

With explicit instantiation, my program should contain an instance even if I don't use it later (assume it's not omitted by compiler optimization).

My question is, does the following statements cause instantiation of the class?

typedef Temp<short> TShort;
using TFloat = Temp<float>; // C++11
Marino answered 5/10, 2017 at 3:12 Comment(0)
N
5

No. Implicit instantiation only occurs when a completely defined type is required; while type alias doesn't have to.

When code refers to a template in context that requires a completely defined type, or when the completeness of the type affects the code, and this particular type has not been explicitly instantiated, implicit instantiation occurs. For example, when an object of this type is constructed, but not when a pointer to this type is constructed.

e.g. The following code requires a completely defined type,

Temp<char> tc;
new Temp<char>;
sizeof(Temp<char>);

while

Temp<char>* ptc;

doesn't.

Nne answered 5/10, 2017 at 3:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.