如何将模板和非模板函数放在一个文件中
How to have template and non-template functions in one file
我有一个带有模板函数和"普通"函数的实用程序文件:
#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
。
相关文章:
- 挂起和取消挂起一个文件DLL
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- C++试图读取一个文件并输出到另一个文本文件
- 如何从另一个文件继承私有成员变量和公共函数
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 如何将class.cpp和class.hpp编译为一个.o文件
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 如何从整个磁盘中排除要装载的一个文件
- 如何将模板和非模板函数放在一个文件中
- 如何在安卓工作室中将c ++头文件从一个文件夹导入到另一个文件夹?
- 使用 scope 运算符 (::) 引用另一个文件中的类
- JNI,使用两个 .so 文件时出错,其中一个文件需要另一个文件
- 为什么我不能从同一目录中的另一个文件中 #include 我的类?
- 在 c++ 中打开文件、删除标点符号并追加到另一个文件中
- C++ 如何将两个 makefile 对象目标规则(位于另一个文件夹中)合并到一个目标/规则中?
- 是否可以将子进程的 stdout 重定向到父进程中的另一个文件?
- c++ 提升如果 .extension() == " "这意味着这个文件是一个文件夹?
- 是否可以在 c++ 中创建一个文件并为其提供属性以将其隐藏?(在 Ubuntu 上)
- 我需要编写一个程序来读取一个文件,该文件将输出所有唯一的整数,如果已经看到整数,它将被关闭
- 如何在标准c ++中流式传输/读取二进制文件的中间部分并写入另一个文件?