c – 这本教科书错了吗?专注于某些成员职能而不是其他职能

我正在阅读Vandevoorde和Josuttis的“C模板完整指南”(顺便说一句,这看起来还不错).这个说法(第3.3节)似乎是错误and is not in the published errata

If you specialise a class template,you must also specialise all member functions. Although it is possible to specialise a single member function,once you have done so,you can no longer specialise the whole class.

然而以下编译在gcc上
模板

<typename T>
struct C {
    T foo ();
    T bar ();
};

template <>
struct C<int> {
    int foo ();
    int bar () {return 4;}
};

template <typename T>
T C<T> :: foo () {return 0;}

template <typename T>
T C<T> :: bar () {return 1;}

int C<int> :: foo () {return 2;}

template <>
float C<float> :: bar () {return 3;}

#include <cassert>

int main () {
    C<int> i;
    C<float> f;
    assert (2 == i .foo ());
    assert (0 == f .foo ());
    assert (4 == i .bar ());
    assert (3 == f .bar ());
}

我有专门的C< int> :: foo和C< float> :: bar所以教科书错了,gcc超出了标准,还是我误解了整个情况?

谢谢.

解决方法

你不能做这个:
template <typename T> struct C
{
   T foo ()     { return 0;}
   T bar ()     { return 1;}
};

// partial specialization of foo on C<int>
template <>
int C<int> :: foo () {return 2;}

// partial specialization of bar on C<float>
template <>
float C<float> :: bar () {return 3;}

// will not compile,C<int> already partially specialized
template <>
struct C<int>
{
   int foo() {return 10;}
   int bar() {return 10;}
};

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...