[cpp] 请问gcc 3.x下的一个模板问题
Wu Yongwei
adah at sh163.net
Wed May 3 00:20:46 CST 2006
rockie wrote:
> 大家好, 有个问题难住了。
> 以下程序打开注释在vc6, vs05下可以通过编译,不知道为什么在gcc 3.x下编译不通过。
> 谢谢指教。
>
> template <typename DataType>
> class FMC
> {
> public:
> ...
> static const DataType Epsilon;
> ...
> private:
> FMC() {}
> };
>
> /*
> template <>
> const float FMC<float>::Epsilon = static_cast<float>(0.000001);
>
> template <>
> const double FMC<double>::Epsilon = static_cast<double>(0.0000000001);
> */
>
> template <typename DataType>
> const DataType FMC<DataType>::Epsilon = static_cast<DataType>(0.000001);
>
> 错误提示是multiple definition
>
> --------------
> rockie
> rockie at student.dlut.edu.cn
> 2006-05-02
我估计你出问题的原因是把被注释掉的代码放到了头文件中,并在多处包含了该头
文件。解决方法是把这些代码移到(只编译、连接一次的)一个 .cpp 文件中。
我认为 GCC 的做法是符合 C++ 标准的。C++1998 标准的 14.7.3.15 这么写的:
An explicit specialization of a static data member of a template is a
definition if the declaration includes an initializer; otherwise, it is
a declaration. [Note: there is no syntax for the definition of a static
data member of a template that requires default initialization.
template<> X Q<int>::x;
This is a declaration regardless of whether X can be default initialized
(8.5). ]
也就是说,被注释掉的这两段代码被视作定义而不是声明。在头文件定义类成员变
量当然是要出问题的。错误 multiple definition 也就正常了。
吴咏炜
More information about the Cpp
mailing list