1

I've read that the body of a template function must be included in the file which actually uses it (i.e., the decleration isn't enough).

Suppose that I define a template function in a header file:

//someheader.h
#ifndef SOME_H
#define SOME_H
template<class T>
void MyTemplateFunc(T *In, ...)
{

//definitions here   

}
#endif

I can actually use it in two different cpp files:

//file1.cpp
#include "someheader.h"
void f1()
{
   //some code
   MyTemplateFunc<int>(Some_int_Pointer);//use template here

}

and

//file2.cpp
#include "someheader.h"
void f2()
{
   //some code
   MyTemplateFunc<float>(Some_float_Pointer);//use template here

}

Now, I am not complaining (just trying to understand) but how come I am not getting compiling/linking error in this case?. Since the double inclusion guard will cause "someheader.h" to be included only in one of the cpp files which in turn will cause the other cpp file to complain that he can't "see" the template definition.

What am I missing here?

Thanks

Benny

4

2 回答 2

1

"Since the double inclusion guard will cause "someheader.h" to be included only in one of the cpp files"

It's false. That guard avoids multiple declarations in a translation unit. So, you have included it in each translation unit once and everything is OK.

In addition you should inline that function in the header file to obey one definition rule.

于 2013-11-13T16:44:21.947 回答
1

在我看来,您的 file1.cpp 和 file2.cpp 是两个不同的文件,彼此独立。

如果出现以下情况,您将收到错误消息,并且您的代码无法运行:

如果你没有使用 ifndef 并且你在 file2.h 中包含了 file1.h ,那么在 file2.h 你有两次声明 someheader.h" 因为它已经在 file1.h 中声明了,

//someheader.h

template<class T>
void MyTemplateFunc(T *In, ...)
{

  //definitions here   

}

file1 头文件

//file1.h
#include "someheader.h"

void f1();

和file2头文件

//file2.h

#include "file1.h" //! note, it already has declared someheader.h
#include "someheader.h" //! you are declaring it again
void f2();

在这种情况下,要解决此类问题,您应该包含 ifndef 或 #pragma 一次,这将导致当前源文件在单个编译中仅包含一次。

于 2017-01-27T06:41:49.700 回答