如何将模板和非模板函数放在一个文件中

How to have template and non-template functions in one file

本文关键字:一个 文件 函数      更新时间:2023-10-16

我有一个带有模板函数和"普通"函数的实用程序文件:

#ifndef __UTILS_CPP__
#define __UTILS_CPP__
#include <stdlib.h>
template<typename T> int makeIntN(const T V) { return (int)V;}
int makeIntS(const char *pVal) { return atoi(pVal);}
#endif

这些函数由另外两个类(子 A 和子 B(使用。

SubA.h

#ifndef __SUBA_H__
#define __SUBA_H__
class SubA {
public:
SubA() {};
static int actionN(int i);
int actionS(const char *p);    
};    
#endif

子.cpp

#include "suba.h"
#include "utils.cpp"
int SubA::actionN(int i) {
return makeIntN(i);
}
int SubA::actionS(const char *p) {
return makeIntS(p);
}

亚C.h

#ifndef __SUBC_H__
#define __SUBC_H__
class SubC {
public:
SubC() {};
int actionN(float f);
static int actionS(const char *p);
};    
#endif

子C.cpp

#include "subc.h"
#include "utils.cpp"
int SubC::actionS(const char *p) {
return makeIntS(p);
}
int SubC::actionN(float f) {
return makeIntN(f);
}

在main((中,我创建了这些类的实例并调用了它们的一些方法:

CLTEST.cpp

#include <stdio.h>
#include "suba.h"
#include "subc.h"
int main() {
int iResult = -1;
SubA *psa = new SubA();
iResult = psa->actionN(17);
printf("Res A: %dn", iResult);
iResult = psa->actionS("17");
printf("Res A: %dn", iResult);
SubC *psc = new SubC();
iResult = psc->actionN(17.65);
printf("Res C: %dn", iResult);
return iResult;
}

当我像这样编译时:g++ clstest.cpp subc.cpp suba.cpp,我显然得到一个错误,因为 makeIntS(( 分别包含在 SubA 和 SubC 中。

我尝试了各种#include方式和不同的链接方式,但要么makeIntN()未定义,要么makeIntS()是多重定义的。

如何在不将 utils 文件拆分为模板部分和非模板部分的情况下对其进行编译和链接?

有3 种方法可以在头文件中定义非模板自由函数:

  • 使函数inline
  • 使函数static
  • 将函数放在匿名命名空间中

我建议你去做一个int makeIntS(const char *pVal);函数inline

相关文章: