C++——我可以使用一个没有在头文件中实现的模板函数吗
C++ -- Can I use a template function that is not implemented in a header file?
可能重复:
将C++模板函数定义存储在.CPP文件中
为什么模板只能在头文件中实现
为什么模板类的实现和声明应该在同一个头文件中?
我有三个档案。在一个base.h中,我有一个类,它有一个使用模板的成员:
class Base {
protected:
template <class T>
void doStuff(T a, int b);
};
在base.cpp中,我实现了base::doStuff():
#include "base.h"
template <class T>
void Base::doStuff(T a, int b) {
a = b;
}
然后我试着在我的项目中的另一个类中使用这个:
#include "base.h"
void Derived::doOtherStuff() {
int c;
doStuff(3, c);
}
但我收到一个链接错误,说它找不到"doStuff(int,int)"
据我所见,如果不将此函数的实现移动到头文件中,这在C++03中是不可能的。有干净的方法吗?(我对使用C++11x功能很满意)。
将模板定义与内联函数定义一起放入.inl
文件中,并将其包含在.h
文件的末尾是一种常见的习惯用法:
base.h
#ifndef BASE_H
#define BASE_H
class Base {
protected:
template <typename T>
void doStuff(T a, int b);
};
#include "base.inl"
#endif
base.inl
template <typename T>
void Base::doStuff(T a, int b) {
a = b;
}
相关文章:
- 在实现文件中使用头文件的通用 lambda
- 如何使用命令提示符、记事本和 MinGW 使用主文件、头文件和实现文件编译C++程序?
- 类中的数组变量C++导致"was not declared in this scope"实现文件的一个函数中错误,但在构造函数中不会导致错误
- 在实现文件中使用模板参数声明方法
- 模板实现文件中的匿名命名空间
- 创建单独的实现文件和头文件
- 当我从头文件和实现文件调用我的函数到我的主文件时,我没有得到任何输出
- 在实现文件中,我们应该更喜欢"using namespace"指令还是将实现包装在命名空间 { } 中?
- 包含适当的标头时,实现文件中的多个定义出错
- 如何在结构中实现文件读取和创建
- 在头文件和实现文件中创建模板模板函数
- C++头/实现文件中的默认和重载构造函数?
- 如何在C++实现文件中实例化类?
- 实现文件只能识别其他类的远期声明
- C++ 将字符串值传递到实现文件时出现问题
- 创建头文件和实现文件时出现问题
- C 从实现文件中访问私有静态成员
- Pimpl习惯用法、单独的接口/实现文件和多个虚拟继承.如何
- 没有实现文件(.cpp)的派生类
- 在标题或实现文件中定义常数的优点