编写下标非成员函数

时间:2019-06-14 14:50:31

标签: c++ operator-overloading non-member-functions subscript-operator

我猜想这在C ++中是不合法的,但是考虑到我不拥有的结构,我想问一下:

struct foo {
    int x;
    int y;
    int z;
};

我想为其编写一个非成员下标运算符:

int& operator [](foo& lhs, const std::size_t rhs) {
    switch(rhs) {
    case 0U:
        return lhs.x;
    case 1U:
        return lhs.y;
    case 2U:
        return lhs.z;
    default:
        return *(&(lhs.z) + rhs - 2U);
    }
}

I'm getting this error

  

错误:int& operator[](foo&, std::size_t)必须是非静态成员函数

2 个答案:

答案 0 :(得分:4)

struct foo {
    int x;
    int y;
    int z;

  int& operator [](const std::size_t rhs) & {
    switch(rhs) {
      case 0U:
        return this->x;
      case 1U:
        return this->y;
      case 2U:
        return this->z;
      default:
        return *(&(this->z) + rhs - 2U);
    }
  }
};

并非所有运算符都可以作为自由函数重载。

运算符[]=->()不是标准的,但明确写在cppreference上,必须是非静态成员函数

如果您可以执行wrap(f)[2],则可以使用它。但是没有办法让它在foo实例上工作。

template<class T>
struct index_wrap_t {
  T t;
  template<class Rhs>
  decltype(auto) operator[](Rhs&& rhs)& {
    return operator_index( *this, std::forward<Rhs>(rhs) );
  }
  template<class Rhs>
  decltype(auto) operator[](Rhs&& rhs)&& {
    return operator_index( std::move(*this), std::forward<Rhs>(rhs) );
  }
  template<class Rhs>
  decltype(auto) operator[](Rhs&& rhs) const& {
    return operator_index( *this, std::forward<Rhs>(rhs) );
  }
  template<class Rhs>
  decltype(auto) operator[](Rhs&& rhs) const&& {
    return operator_index( std::move(*this), std::forward<Rhs>(rhs) );
  }
};

template<class T>
index_wrap_t<T> index( T&& t ) { return {std::forward<T>(t)}; }

然后您可以执行以下操作:

int& operator_index( foo& lhs, std::size_t rhs ) {
  // your body goes here
}
foo f;
index(f)[1] = 2;

它有效。

index_wrap_t转发[]到对进行ADL的operator_index的免费呼叫。

答案 1 :(得分:1)

您可以拥有包装器类和函数:

struct foo_wrapper {
    foo &ref;

    foo_wrapper( foo &f ) : ref( f ) {}
    int &operator[]( std::size_t rhs ) {
       switch(rhs) {
       case 0U:
           return ref.x;
       case 1U:
           return ref.y;
       case 2U:
           return ref.z;
       default:
           return *(&(ref.z) + rhs - 2U);
        }
    }    
};

foo_wrapper wrap( foo &ff )
{
    return foo_wrapper( ff );
}

foo f;
wrap( f )[1] = 123;

Live example 您可能需要直接编写此辅助函数:

foo_wrapper( f )[2] = 0; 

会导致编译错误(重新声明f)