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.
You cannot do this:
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;}
};
No, the book isn't wrong. Your understanding is, I am afraid :)
In this case you have specialized only 1 member function - foo
for C<int>
and bar
for C<float>
Now you can't explicitly specialize C<int>
or C<float>
. But you can specialize C<char>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With