11

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?

Mircea Ispas
  • 20,260
  • 32
  • 123
  • 211
  • What is the purpose of `friend T;` string in your example code? – Constructor Apr 03 '14 at 12:21
  • @Constructor sometimes you want someone to have private access in the class, but you don't know who:) Consider the observer patter - anybody can register listeners to some event, but only somebody should be able to trigger the event. When implementing Event class you don't know who will trigger the event, but you can consider the "ONE" will be some kind of class/structure. – Mircea Ispas Apr 03 '14 at 12:26
  • The standard says nothing about implementation details like these, it all comes down to what each compiler decides to do. – Matteo Italia Apr 03 '14 at 12:32
  • DUP http://stackoverflow.com/q/15168924/377657 – rwong Apr 03 '14 at 12:34
  • @Felics I know what this string mean and what purpose it *may* have. I don't understand how it relates to *this* example. – Constructor Apr 03 '14 at 12:38
  • 1
    @Constructor This is just an example, as you say, to make it obvious that generated code doesn't depends on T. – Mircea Ispas Apr 03 '14 at 12:42

1 Answers1

8

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.

David K
  • 3,147
  • 2
  • 13
  • 19
  • Very good advice to be sure I won't have code duplicate for non template part, +1. I won't vote this as accepted because it doesn't answer my question:) – Mircea Ispas Apr 03 '14 at 12:29
  • Fair enough; I was going for "useful" rather than "answer". For the actual question, the only answer answer I'd trust would be one found by experimenting with the compiler you want to use. – David K Apr 03 '14 at 13:02