为什么不允许"空属性块"?

Rob*_*son 2 c++ syntax

这可能是今天提出的最愚蠢的问题,但无论如何我都要按下:

以下带有重载运算符的派生类,其重载运算符+=的基类[]给出以下编译器错误:

不允许使用空属性块

我当然会写v[0]v[1]操作员+=,但是我很好奇它是否会编译,如果没有,为什么不.

什么是属性块?为什么编译器不解析[0][]运算符,从基类返回引用?只是语法问题或更深层次的问题?

#include <array>

template<class T, int C>
struct Vec
{
    typedef T value_type;
    typedef unsigned index_type;
    typedef unsigned size_type;

    std::array<T, C> v;

    template<typename ...Args>
    explicit Vec(Args&&... args) : v({{args...}}) {}
    Vec(std::array<T, C> const & o) : v(o) {}

    value_type & operator [] (index_type i)
    {           
        return v[i];
    }

    value_type const & operator [] (index_type i) const
    {
        return v[i];
    }
}; 

template<class T>
struct Vec2 : Vec<T, 2>
{
    template<typename ...Args>
    explicit Vec2(Args... args) : Vec<T, 2>(args...) {}
    Vec2(Vec2<T> const & p) : Vec<T, 2>(p.v) {}     

    Vec2<T> & operator += (Vec2<T> const & q)
    {
        [0] += q[0];
        [1] += q[1];

        return *this;
    }
};

int main(void)
{
    Vec2<int> a(10, 20);
    Vec2<int> b(30, 40);

    a += b;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Pup*_*ppy 5

您不能以这种方式使用运算符自由形式.你必须this明确提供,例如(*this)[0].引用属性的错误消息只是因为[]也可以用来表示属性.