chacham15
chacham15

Reputation: 14251

How does a template appear in a translation unit?

If I have a templated class definition in list.h:

template <class T>;
class list {
    list *next;
    T *data;

    list(T *data){
        this->next = NULL;
        this->data = data;
    }
    void concat(T *data){
        this->concat(new list<T>(data));
    }
    void concat(list<T> *sublist){
        if (this->next != NULL){
            this->next->concat(sublist);
        } else {
            this->next = sublist;
        }
    }
}

Then if I have main.cpp:

class bar {
    bar(){

    }
}

class baz {
    baz(){

    }
}

void main(){
    new list<bar>(new bar());
    new list<baz>(new baz());
}

And then I ran:

gcc -c main.cpp
  1. How does the code get put into translation units?
  2. Does the translation unit of main.cpp have 2 versions of list?
  3. What if list we included in another translation unit, would it appear in both?

Upvotes: 0

Views: 644

Answers (1)

Dan
Dan

Reputation: 2528

When you specialize the template the code will be placed in the translation unit where the specialization occurs.

If you use a template over and over in separate translation units, you will find that each translation unit gets a copy of the code. This is called code bloat, and is one of the major drawbacks to template use.

You can declare template specializations, and place the code for those inside a single translation unit, but then you will not be able to create new specializations with out the same linker issue you have here.

To # 2: Some compilers will use a single definition when the types are similar enough. For example storing a pointer. You can create a dozen different pointer types and only the code that handles them as separate types will need to be replicated with type specialization. But this is highly compiler dependent.

Upvotes: 4

Related Questions