Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ code generation for non template dependent code

Tags:

c++

templates

Considering the following code:

template<typename T>
struct A
{
    void f(){...}

    friend T;
};

template<typename T>
struct B
{
    void f(T){...}//code depends on T
    void g(){...}//code doesn't depends on T
}

As you see, the "code" in the struct A doesn't depend on T. Will the compiler generate different code in the final binary for every T used to instantiate A?

Same question for B::g() function, will the compiler use the same function for all instances of B<T> when it's possible, for example this is not used in g(), so no dependency on T? Does the standard have any specification for this case?

like image 671
Mircea Ispas Avatar asked Apr 03 '14 12:04

Mircea Ispas


1 Answers

If you want to be sure what the compiler generates, why not write a non-template struct implementing the code that doesn't depend on T, and then derive your template from the non-template? You get one copy of the non-template code, which each instance of the template inherits.

At least, that's what I've done in the past when I found that template instantiation was making my compiled objects very large.

like image 121
David K Avatar answered Oct 20 '22 04:10

David K