Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this textbook wrong? Specialising some member functions but not others

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.

like image 346
spraff Avatar asked Aug 03 '11 16:08

spraff


2 Answers

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;}
};
like image 163
Chad Avatar answered Sep 21 '22 02:09

Chad


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>

like image 39
Armen Tsirunyan Avatar answered Sep 21 '22 02:09

Armen Tsirunyan