c++ - 包括模板函数

标签 c++ templates compilation linker header-files

我读到模板函数的主体必须包含在实际使用它的文件中(即 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/

相关文章:

c++ - 构造函数定义中类声明的模板值

java - 用于独立于系统的程序分发的即时 C++ 编译器

jenkins - 如何将Groovy变量用于Extended Choice Jenkins插件?

c++ - 确定NaN(不是数字值)

c++ - 如何从dll中的异步函数返回值

c++ - 基于策略的模板设计 : How to access certain policies of the class?

C++ : friend declaration ‘declares a non-template function

java - 系统崩溃后 Eclipse 行为不一致

c++ - QtCreator : Loading External Library

c++ - std::hash<string> 的时间复杂度是多少