Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do typedef and using cause a template instantiation?

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
like image 986
iBug Avatar asked Oct 05 '17 03:10

iBug


Video Answer


1 Answers

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.

like image 69
songyuanyao Avatar answered Sep 21 '22 04:09

songyuanyao