book example doesn't compile

Here I have an example code from Stroustroups PPP-book, but it doesn't compile.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <vector>
#include <stdexcept>

struct Range_error : std::out_of_range
{
    int index;
    Range_error(int i)
    : out_of_range{"Range_error"}, index{i}
    {}
};

/*
 *  Adding range error check for operator[].
 */
 
template <typename T>
struct Vector : public std::vector<T>
{
    using size_type = typename std::vector<T>::size_type;
    using std::vector<T>::vector;
    
    T& operator[]( size_type i)
    {
        if ( i < 0 || this.size() <= i )
        {
            throw Range_error{ i };
        }
        return std::vector<T>::operator[]( i );
    }
    
    const T& operator[]( size_type i) const
    {
        if (i < 0 || this.size() <= i )
        {
            throw Range_error{ i };
        }
        return std::vector<T>::operator[]( i );
    }
};

int main()
{
    Vector<char> v(8);
    v[8] = '\0';   // Range_error throw expected.
}

Here my compiler messages:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Vector.cpp:24:27: error: member reference base type 'Vector<T> *' is not a
      structure or union
        if ( i < 0 || this.size() <= i )
                      ~~~~^~~~~
Vector.cpp:33:26: error: member reference base type 'const Vector<T> *' is not a
      structure or union
        if (i < 0 || this.size() <= i )
                     ~~~~^~~~~
Vector.cpp:26:32: error: non-constant-expression cannot be narrowed from type
      'size_type' (aka 'unsigned long') to 'int' in initializer list
      [-Wc++11-narrowing]
            throw Range_error{ i };
                               ^
Vector.cpp:44:6: note: in instantiation of member function
      'Vector<char>::operator[]' requested here
    v[8] = '\0';   // Range_error throw expected.
     ^
Vector.cpp:26:32: note: insert an explicit cast to silence this issue
            throw Range_error{ i };
                               ^
                               static_cast<int>( )
3 errors generated.
Last edited on
this is a pointer so either you have to use the * operator before calling the function ...

 
(*this).size()

... or you could use the -> operator which will do the same thing but is a bit shorter to write.

 
this->size()
Thank you, Peter. I must been blind for that i did'nt have seen this huge mistake.
Topic archived. No new replies allowed.