Hemant Bhargava
Hemant Bhargava

Reputation: 3585

Difference between templates and two separate classes

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?

Upvotes: 6

Views: 207

Answers (2)

Vijeth
Vijeth

Reputation: 410

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.

Upvotes: 1

rustyx
rustyx

Reputation: 85361

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.

Upvotes: 8

Related Questions