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

问题描述

我有 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 (将#修改为@)