jeudi 18 octobre 2018

Avoid redefinition error in template class

For IO purposes, I need to associate to various type a character string. To this end, I created a template class names, which is specialized for each type I need to name. Here is the header file:

template<typename T>
class names {};

template<>
class names<Index> {
public:
    static const std::string name;
};

template<>
class names<Integer> {
public:
    static const std::string name;
};

And the corresponding source file:

const std::string names<Index>::name = "Index";

const std::string names<Integer>::name = "Integer";

Index and Integer are defined via a typedef:

typedef std::ptrdiff_t Index;

typedef int Integer;

The code compiles and runs fine on the macOS and Ubuntu machines I use. However, on a Windows machine, std::ptrdiff_t is defined as an int. I then get the following error:

In file included from lib/mixt_MixtComp.h:22:0,
                 from dummy.cpp:5:
lib/LinAlg/names.h:28:7: error: redefinition of 'class mixt::names<int>'
 class names<Integer> {
       ^
lib/LinAlg/names.h:22:7: error: previous definition of 'class mixt::names<int>'
 class names<Index> {
       ^

Is there a way to avoid this error ? I can use C++11.

Aucun commentaire:

Enregistrer un commentaire