如何解决如何解决标头中模板特化的未定义引用错误?
我有 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`
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。