尽管覆盖,但编译错误

时间:2015-01-23 11:23:03

标签: c++ inheritance c++11 polymorphism override

很抱歉,如果这是一个非常简单的问题,那么在c ++中一定有一些我不了解的继承,virtualoverride。在下面的示例中,我得到一个相对于我专门覆盖的虚方法的编译时错误,以避免在子类中出现此类错误。难道我做错了什么?

#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] ); }
};

/**
 * The implementation of foo::operator[] is useful for classes inheriting
 * with simple sequence containers like:
 *  foo<T,std::deque<T>>, foo<T,std::vector<T>>, ..
 *
 * But the following requires operator[] to be redefined:
 */

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 virtual T& operator[] ( unsigned n ) const override
        { return const_cast<T&>( data()[n/N][n%N] ); }
};

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

编辑1 错误:

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.

编辑2 我认为这是问题的一部分;如果由于foo::operator[]中的baz仍然可以调用而导致编译失败,那么为什么如果我foo::operator[]声明为虚拟,则为什么编译正常(即隐藏压倒一切?

1 个答案:

答案 0 :(得分:3)

问题在于,虽然您只打算在operator[]实例上调用派生的baz函数,但编译器仍需要为基类生成代码,因为该函数仍可在{{{ 1}}实例。在这种情况下,生成该代码会导致类型错误,因为您尝试将baz转换为const std::array<double,3>

为了解决这个问题,您应该拥有层次结构的不同部分,这些部分定义了一个适用于其所有子节点的运算符,如此(删除了非相关内容):

double&

这种方式如果你想要稍后添加任何其他版本,你可以从bar或baz派生,而不需要为每个孩子定义运算符。

相关问题