c++ - 如何解决标头中模板特化的未定义引用错误?
问题描述
我有 4 个文件Colors.h
, ColorUtils.h
, Paintbrush.h
, 和Paintbrush.cpp
Colors.h
定义了颜色的枚举COLOR_NAMES
和一些颜色类Red
, Yellow
, Blue
.
在Utils.h
我有一个模板旨在返回基于类型的枚举值。
// ColorUtils.h
#include "Colors.h"
namespace COLORS {
template <class T> struct TypeToEnum {};
template<> struct TypeToEnum<Red> { static const COLOR_NAMES color = COLOR_NAMES::RED; };
template<> struct TypeToEnum<Yellow> { static const COLOR_NAMES color = COLOR_NAMES::YELLOW; };
template<> struct TypeToEnum<Blue> { static const COLOR_NAMES color = COLOR_NAMES::BLUE; };
}
在Paintbrush.h
我尝试使用这些模板特化。
// Paintbrush.h
#include "Colors.h"
#include "ColorUtils.h"
namespace COLORS {
class Paintbrush {
public: doSomething();
template <class T>
void printColor { std::cout << to_string(TypeToEnum<T>::color) << std::endl; }
};
}
在Paintbrush.cpp
我使用依赖于模板特化的标题中定义的函数模板Utils.h
// Paintbrush.cpp
#include "Paintbrush.h"
Paintbrush::doSomething() {
printColor<Red>();
printColor<Yellow>();
printColor<Blue>();
}
此设置引发了很多链接器错误,本质上是:
Paintbrush.o: In function `void Paintbrush::printColor<Red>(): ...
Paintbrush.cpp: ...undefined reference to `COLORS::TypeToEnum<COLORS::Red>::color`
解决方案
推荐阅读
- node.js - 从节点服务器流式传输图像数据会导致文件损坏 (gridfs-stream)
- python - 每第 N 次迭代写入不同的文件?
- r - .Rprofile 没有来源
- swift - 为什么更新视图时我的数组是空的?(迅速)
- server-side - Gtag.js optmize server_side 实现不起作用
- php - 我正在使用 foreach 遍历一个数组并向每个号码发送短信,但不能这样做。它只发送给一个
- javafx - 向应用程序中的多个场景添加 CSS
- grails - 是否有将 Java Struts 1 应用程序转换为 Grails 的已知过程
- java - 相同的代码在 java 中有效,但在 android 中无效
- python-3.x - LaTeX 无法在 python 中处理字符串