mercredi 14 juillet 2021

How do I resolve undefined reference errors for template specializations in header? [duplicate]

I have 4 files Colors.h, ColorUtils.h, Paintbrush.h, and Paintbrush.cpp

Colors.h defines an enumeration of colors COLOR_NAMES and some color classes Red, Yellow, Blue.

In Utils.h I have a template designed to return an enum value based on a type.

// 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; };
}

In Paintbrush.h I try to use these template specializations.

// 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; }
    };
}

In Paintbrush.cpp I use the function template defined in the header that relies on the template specializations in Utils.h

// Paintbrush.cpp
#include "Paintbrush.h"

Paintbrush::doSomething() {
    printColor<Red>();
    printColor<Yellow>();
    printColor<Blue>();
}

This setup is throwing a lot of linker errors, essentially:

Paintbrush.o: In function `void Paintbrush::printColor<Red>(): ...
Paintbrush.cpp: ...undefined reference to `COLORS::TypeToEnum<COLORS::Red>::color`

Aucun commentaire:

Enregistrer un commentaire