Is this tutorial wrong? Specialization of some member functions but not others

I read Vandevoorde and Josuttis "C ++ Templates The Complete Guide" (which, by the way, seems pretty good). This statement (section 3.3) seems incorrect and is not in the published errors :

If you specialize in a class template, you must also specialize all member functions. Although you can specialize one member function as soon as you do this, you can no longer specialize the entire class.

However, the following compilation on the 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 specialized C<int>::foo and C<float>::bar , so the wrong tutorial, gcc is beyond the standard, or I don’t understand the whole situation?

Thanks.

+6
source share
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;} }; 
+5
source

No, the book is not mistaken. Your understanding, I'm afraid :)

In this case, you have specialized only one member function - foo for C<int> and bar for C<float>

Now you cannot explicitly specialize C<int> or C<float> . But you can specialize C<char>

+4
source

Source: https://habr.com/ru/post/894204/


All Articles