开发者

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

开发者 https://www.devze.com 2023-03-25 11:33 出处:网络
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:

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<i开发者_如何学运维nt> :: 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>

0

精彩评论

暂无评论...
验证码 换一张
取 消