在.h文件中定义模板,在.h文件中声明并在.cpp文件中定义

时间:2019-03-18 11:08:45

标签: c++ templates include

我有看起来像这样的代码(使用Arduino IDE编译)。

主草图文件:

#include "myHeader.h"

//setup stuff here, including setting up Serial & SerialBT

loop(){
  CheckForMessages(&Serial);   //Check USB first
  CheckForMessages(&SerialBT); //Then check Bluetooth
}

myHeader.h:

#include "Arduino.h"
//other includes

template <class T> void CheckForMessages(T *port);

//declarations of other stuff

myHeader.cpp:

#include "myHeader.h"

template <class T> void CheckForMessages(T *port){
  if(port->available() !=0){
    //rest of function...
}

//definitions of other stuff

编译时,在主草图文件中两次调用CheckForMessages时都收到“未定义参考”错误。如果我将模板的定义移到.h文件中,这将消失。

据我所知,以这种方式拆分函数的声明和定义没有问题,有人可以向我解释为什么它不适用于我的模板吗?

0 个答案:

没有答案