views:

139

answers:

3

Starting with sth's answer to this question:

I was wondering how to resolve multiple definition errors if the following code is put in a header file included multiple times by different .cc files and linked together:

template <typename T>
class C {
   static const int K;
   static ostream& print(ostream& os, const T& t) { return os << t;}
};

// general case
template <typename T>
const int C<T>::K = 1;

// specialization
template <>
const int C<int>::K = 2;
+1  A: 

Move specialization into one of the .cc files. Leave template version in header.

Paul
How would this work? What if I needed the specializations in multiple .cc files ? Then I get an error when I link multiple .cc files with the same definitions.
@user231536: If you write a normal class you provide methods definitions only in one .cc, linker makes it possible to use them from the rest of .cc files. The same works for full specializations. You provide specialization only in one .cc file, linker ensures other .cc files can use it.
Paul
A: 

Depending on the platform, you could surround it by a #ifdef or a something like #pragma once

Daryl
A: 

The only thing I can think of is that you're defining the K variable for all types before any specialization, and so when the compiler would get to the <int> specialization, the variable definition would already exist..

So, if that is the case, you'll want to move the specialization for C<int>::K to before C<T>::K

ianmac45