Avinash
Avinash

Reputation: 13257

C++ template and ODR Rule

Why does following works in C++, I thought ODR rule will come into picture for following code

typedef char      int8; 
class Sample {
public:
  template <typename T>
  void test( T param){
  }
};

int main() {
  Sample s;
  s.test<char>('a');
  s.test<int8>((int8)'b');
  return 0;
}

Upvotes: 2

Views: 439

Answers (2)

jrok
jrok

Reputation: 55395

Because when the template instantiations are done and compiler gets rid of typedefs and unnecessary casts, your code is exactly the same as:

class Sample {
public:
  void test(char param){
  }
};

int main() {
  Sample s;
  s.test('a');
  s.test('b');
  return 0;
}

You seem to think that a typedef declares another distinct type, but that's not the case. It's just an alias (for your convinience, usually). OTOH, when you call a function template with a different template parameter, functions with different signatures are generated. No ODR violation in either case.

Upvotes: 2

Qaz
Qaz

Reputation: 61920

It's doing the same thing both times. It just looks like they're different.

The first one says it'll use the char version, so T becomes a char.

The second says it'll use the int8 version, so T would become an int8, which is actually just a char in disguise. Therefore, T will still be a char, and you're passing in a char in both cases, so all is well.

Upvotes: 1

Related Questions