Subscript operator issues

Hi,


I've made a class that inherits std::vector, to make it more like C#'s List.
But the subscript operator is given me trouble, that I can't figure out.
Especially as the code worked fine in my test project.

From List.h

template<class T> class List : protected std::vector<T>
{
/* unimportant stuff */

T &operator[]( const int i )
{
assert( i >= 0 && i < Count() );
return vector::operator[]( i );
}
};


And this where I'm getting the error:
error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const List<Matrix4>' (or there is no acceptable conversion)

float *RenderObject::TransformData( int index ) const
{
assert( index < transforms.Count() );
return (float*)&transforms[index];
}

I'm not getting this in my test project. How come?
Last edited on
You get an error because you have not mentioned the template argument of vector.

 
return vector<T>::operator[]( i );

Template code is usually not instantiated until you use it. Your test program probably didn't use the List<T>::operator[] so the code in that function was never fully evaluated.
Last edited on
I've unfortunately already tried this, and still been getting the same error. The test program does actually use the [] operator. I delibrately changed a section of the code there to do so, but still not having that issue.

From the test program
void Display( List<Item> list )
{
cout
<< "# Contents" << endl
<< "----------" << endl;
for( int i = 0; i < list.Count(); i++ )
{
cout << i << " " << list[ i ].Name() << endl;
}
cout << endl;
}
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
#include <iostream>
#include <vector>
#include <cassert>
#include <iostream>

template < typename T > struct ArrayList : private std::vector<T>
{
    using base = std::vector<T> ;
    using base::base ;
    using size_type = typename base::size_type ;
    using base::size ;
    using base::begin ;
    using base::end ;
    // etc. etc.

    typename base::reference operator[] ( size_type pos )
    {
        assert( pos < base::size() ) ;
        return base::at(pos) ; // bound-checked access; may throw std::out_of_range
    }

    typename base::const_reference operator[] ( size_type pos ) const
    {
        assert( pos < base::size() ) ;
        return base::at(pos) ; // bound-checked access; may throw std::out_of_range
    }
};

int main()
{
    ArrayList<int> a { 0, 1, 2, 3, 4, 5 } ;
    const ArrayList<int>& ca = a ;
    assert( a[2] == 2 && ca[3] == 3 ) ;

    for( std::size_t i = 0 ; i < a.size() ; ++i ) a[i] *= i ;

    for( int v : ca ) std::cout << v << ' ' ;
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/ce49316a1df8f9c1
Thank you, that got it working
Last edited on
Topic archived. No new replies allowed.