Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between templates and two separate classes

Tags:

c++

Let us assume this small piece of code:

#include<iostream>

template <typename T>
class A {
  T a;
};

int main() {
  A<int> a;
  A<char> c;
}

Now, consider this code where instead of templates, I have two separate classes for int and char.

#include<iostream>

class A {
  int a;
};

class C {
  char c;
};

int main() {
  A a;
  C c;
}

Would there be any difference in the above two approaches as per compiler, optimization or code segment of the program?

In which approach executable size would be larger and why?

like image 509
Hemant Bhargava Avatar asked Feb 18 '19 11:02

Hemant Bhargava


2 Answers

Templates are essentially a mechanism for source code generation, before the code is compiled.

The two approaches are identical from the perspective of code generation or executable size (except in the first case both classes get a member variable a, and in the second a and c).

Compare variant 1 with variant 2. Notice identical generated code.

like image 114
rustyx Avatar answered Sep 28 '22 05:09

rustyx


Templates will be resolved at compile time based on the inputs present in the code, so executable size should be same in both the cases, unless there are some name differences present.

In your case, I think it should remain same.

like image 26
Vijeth PO Avatar answered Sep 28 '22 07:09

Vijeth PO