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

问题描述

我有 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`

标签: c++c++11templateslinker-errors

解决方案


推荐阅读