我读到模板函数的主体必须包含在实际使用它的文件中(即 decleration 是不够的)。
假设我在头文件中定义了一个模板函数:
//someheader.h
#ifndef SOME_H
#define SOME_H
template<class T>
void MyTemplateFunc(T *In, ...)
{
//definitions here
}
#endif
我实际上可以在两个不同的 cpp 文件中使用它:
//file1.cpp
#include "someheader.h"
void f1()
{
//some code
MyTemplateFunc<int>(Some_int_Pointer);//use template here
}
和
//file2.cpp
#include "someheader.h"
void f2()
{
//some code
MyTemplateFunc<float>(Some_float_Pointer);//use template here
}
现在,我不是在提示(只是想理解),但在这种情况下我怎么没有遇到编译/链接错误?。由于双重包含保护将导致“someheader.h”仅包含在一个 cpp 文件中,这反过来又会导致另一个 cpp 文件提示他无法“看到”模板定义。
我在这里错过了什么?
谢谢
本尼
最佳答案
"Since the double inclusion guard will cause "someheader.h" to be included only in one of the cpp files"
这是假的。该守卫避免在翻译单元 中进行多次声明。因此,您已将其包含在每个翻译单元中一次,一切正常。
此外,您应该在头文件中内联
该函数以遵守一个定义规则。
关于c++ - 包括模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19959159/