0

I have a template functions defined in a header file under a namespace. When I include this header in two source file in the same project. I don't get redefinition error.

/* template.h */
namespace x 
{
   template<typename T>
   function(t)
   {
       /* implementation */
   }
}

/*test.cpp*/
#include "template.h"

/* test2.cpp */
#inlcude "template.h"

In the above case I don't get any redefinition error. .Why I am not receiving any error?

dheeraj Vadlani
  • 377
  • 2
  • 13
  • 1
    That's because you don't define a *function* in your header file, you define a function *template*. I suggest you read e.g. [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) for some more information. – Some programmer dude Mar 09 '17 at 08:54
  • i dont understand - are you asking WHY you are NOT getting error? or what? Since header file included once in each cpp file, there is no redefinition - each cpp sees this header only once, so it is ok.... – Boris Bolshem Mar 09 '17 at 08:55
  • What happens when I include template.h in multiple source files @Someprogrammerdude – dheeraj Vadlani Mar 09 '17 at 09:03
  • 1
    it is ok to include header file to several source file. Each source file will get its own implementation – Boris Bolshem Mar 09 '17 at 09:04

2 Answers2

2

Because implicit template instantiations behave as if they were implicitly inline: all of them are consolidated into a single one at link-time.

Quentin
  • 62,093
  • 7
  • 131
  • 191
0

Define the Header fine in the inner header file, when you include the inner header file to outer file all the headers will be included.

#ifndef FILE_H
#define FILE_H

/* ... Declarations etc here ... */

#endif
Awais Rafique
  • 466
  • 6
  • 17