C++ specialized method templates produce multiple definition errors

Viewed 193

I am using C++ 98. I am writing a JSON object wrapper. For all normal numbers, they can use the same function, but for floats and doubles, I need a seperate function. Same for strings. I wrote this using templates and specialization, and it compiles fine, but when I build my entire project I get about 1 billion errors about multiple definitions. I assume I am not specializing properly. I was able to compile this file with and without having these definitions within the class object itself, so I don't even know if those are required.

class Object {
    public:
        template <class T>
        bool Set(std::string key, T value);
        // having these defined or not doesn't seem to matter
        bool Set(std::string key, double value);
        bool Set(std::string key, float value);
        bool Set(std::string key, std::string value);
};


template <class T>
bool Object::Set(std::string key, T value){
}

template <>
bool Object::Set<double>(std::string key, double value){
}


template <>
bool Object::Set<float>(std::string key, float value){
}

template <>
bool Object::Set<std::string>(std::string key, std::string value){
}

How do I properly specialize these templates so that the compiler/linker doesn't have a fit?

1 Answers

If you define specializations of a member function of a template outside the class in a header file, you need to make the specializations inline like this:

template <> 
inline bool Object::Set<double>(std::string key, double value){
}

template <>
inline bool Object::Set<float>(std::string key, float value){
}

template <>
inline bool Object::Set<std::string>(std::string key, std::string value){
}
Related