C ++多重定义错误

时间:2010-06-14 17:46:26

标签: c++ multiple-definition-error

从这个问题的答案开始:

如果以下代码,我想知道如何解决多个定义错误 将不同的.cc文件多次包含在头文件中并链接在一起:

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;

3 个答案:

答案 0 :(得分:2)

将专业化移动到其中一个.cc文件中。将模板版本保留在标题中。

答案 1 :(得分:0)

根据平台的不同,您可以使用#ifdef或类似#pragma之类的东西将其包围

答案 2 :(得分:0)

我唯一能想到的是你在任何特化之前为所有类型定义K变量,所以当编译器到达{{1}时} specialization,变量定义已经存在..

因此,如果是这种情况,您需要将<int>的专业化移至C<int>::K之前