这本教科书有错吗?专门化某些成员函数,但不专门化其他成员函数
我正在阅读 Vandevoorde 和 Josuttis 的“C++ 模板完整指南”(顺便说一句,这看起来相当不错)。这种说法(第 3.3 节)似乎是错误的并且不在已发布的勘误表中:
如果您专门化一个类模板,则还必须专门化所有成员函数。虽然可以专门化单个成员函数,但一旦这样做,就不能再专门化整个类。
然而下面的代码在 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
和 C
所以教科书是错误的,gcc 超出了标准,还是我误解了整个情况?
谢谢。
I'm reading Vandevoorde and Josuttis's "C++ Templates The Complete Guide" (which seems pretty good, by the way). This claim (section 3.3) seems to be wrong 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.
Yet the following compiles on gcc
template
<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 ());
}
I have specialised C<int>::foo
and C<float>::bar
so is the textbook wrong, is gcc going beyond the standard, or am I misunderstanding the whole situation?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能这样做:
You cannot do this:
不,这本书没有错。恐怕你的理解是:)
在这种情况下,你有专门的只有1个成员函数 -
foo
forC;
和bar
用于C
现在您无法显式特化
C
或C
。但您可以专门化C
No, the book isn't wrong. Your understanding is, I am afraid :)
In this case you have specialized only 1 member function -
foo
forC<int>
andbar
forC<float>
Now you can't explicitly specialize
C<int>
orC<float>
. But you can specializeC<char>