C++ multiple definition error
Starting with sth's answer to this question:
- C++ template specialization
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;
// specializatio开发者_如何学运维n
template <>
const int C<int>::K = 2;
Move specialization into one of the .cc files. Leave template version in header.
Depending on the platform, you could surround it by a #ifdef or a something like #pragma once
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
精彩评论