vendredi 23 janvier 2015

Compile error despite override

Sorry if this is such an easy question, there must be something I don't understand about inheritance, virtual and override in c++. In the following example, I get a compile-time error relative to a virtual method that I specifically override to avoid such error in a child class. Am I doing something wrong?



#include <array>
#include <deque>

template <class T, class C>
struct foo
{
virtual const C& data() const =0;

inline virtual T& operator[] ( unsigned n ) const
{ return const_cast<T&>( data()[n] ); }
};

template <class T>
struct bar
: public foo<T,std::deque<T>>
{
typedef std::deque<T> data_type;
data_type m_data;

inline const data_type& data() const
{ return m_data; }
};

template <class T, unsigned N>
struct baz
: public foo<T, std::deque<std::array<T,N>> >
{
typedef std::deque<std::array<T,N>> data_type;
data_type m_data;

inline const data_type& data() const
{ return m_data; }
inline T& operator[] ( unsigned n ) const override
{ return const_cast<T&>( data()[n/N][n%N] ); }
};

int main()
{
bar<double> a;
baz<double,3> b; // throws an error related to foo::operator[] depsite override
}


Here is the error:



clang++ -std=c++0x -Wall virtual_operator.cpp -o virtual_operator.o
virtual_operator.cpp:11:12: error: const_cast from 'const value_type' (aka 'const std::__1::array<double, 3>') to 'double &' is not allowed
{ return const_cast<T&>( data()[n] ); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~
virtual_operator.cpp:26:8: note: in instantiation of member function 'foo<double, std::__1::deque<std::__1::array<double, 3>, std::__1::allocator<std::__1::array<double, 3> > > >::operator[]'
requested here
struct baz
^
1 error generated.

Aucun commentaire:

Enregistrer un commentaire