gpt4 book ai didi

c++ - 这本教科书错了吗?专门化某些成员函数而不是其他成员函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:22:34 25 4
gpt4 key购买 nike

我正在阅读 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>::fooC<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++ - 这本教科书错了吗?专门化某些成员函数而不是其他成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6930039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com