微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何解决标头中模板特化的未定义引用错误?

如何解决如何解决标头中模板特化的未定义引用错误?

我有 4 个文件 Colors.hColorUtils.hPaintbrush.hPaintbrush.cpp

Colors.h 定义了颜色 COLOR_NAMES 和一些颜色类 RedYellowBlue 的枚举。

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 举报,一经查实,本站将立刻删除。