-2

I have created my first template class, from which both class A and class B descend. Now, in C.h i include both A.h and B.h

As explained here you can only use the same template once per translation unit. I understand that - but how do I prevent the error above? Since A and B use the same template in their class definition lines, they will both be pulled into the same C.h file. I don't see how I can split this into multiple files.

Do I need to put an include guard in the template .h file? (But then how will the second usage of the template know the T in class is different?

TSG
  • 4,242
  • 9
  • 61
  • 121
  • 1
    please post an [mcve] . You didn't even say what the error was. You put a header/include guard on *EVERY* header file. – xaxxon Apr 30 '19 at 01:40
  • 1
    Yes, you need an include guard. Your parenthetical note at the end suggests that you have some misunderstanding of what templates are, but I can't figure out what. :-/ – ruakh Apr 30 '19 at 01:41
  • The error is in the title of this question. – TSG Apr 30 '19 at 01:42
  • @ruakh - yes include guard worked, but I'm confused. Does that mean the template only needs to be included once, and each time it is used the compiler substitutes the T for that specific usage? – TSG Apr 30 '19 at 01:44
  • 1
    @TSG Without include guards, what would happen if you did this: `#include "header.h"` followed by another `#include "header.h"`? See any potential issues with that? If you do, then that's why include guards are used. – PaulMcKenzie Apr 30 '19 at 01:48

1 Answers1

0

Does that mean the template only needs to be included once, and each time it is used the compiler substitutes the T for that specific usage?

Yes, that's the whole point of a class template; you just define it once (plus any specializations), and the compiler generates a separate class for each distinct instantiation of the template.

For example, this:

template<class T>
class Foo {
};

allows you to then write Foo<int>, Foo<long>, Foo<std::string>, Foo<Foo<int> *>, etc., etc., and the compiler will generate the requisite class for each.

ruakh
  • 175,680
  • 26
  • 273
  • 307