Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do C++ template classes duplicate code for each pointer type used?

Tags:

c++

templates

From what I understand, if you have, for example, an std::vector<int> and an std::vector<float>, the compiler creates two classes, one for each type. Thus, although you reduce the amount of code written, you do not reduce executable size (correct me if I'm wrong).

Is the same true even if the type is a pointer? For example, would instantiating an std::vector<SomeClass*> and an std::vector<SomeOtherClass*> necessarily cause the compiler to generate separate code for each of the two instantiations?

like image 955
Anthony Avatar asked Dec 17 '12 12:12

Anthony


1 Answers

This is an implementation dependent as-if optimization and, as thus, is permitted!

In fact, this does not even have to be done by the compiler. The standard library can implemented that way. For example, an implementation could use std::is_pointer and then defer everything to a single void* based implementation. (This is the Thin Template idiom). In fact, doing this on the library side seems to be more feasible than the compiler merging code after instantiating it, but that is possible as well.

like image 86
ltjax Avatar answered Oct 04 '22 22:10

ltjax