编写下标非成员函数

Writing a subscript non-member function

本文关键字:成员 函数 下标      更新时间:2023-10-16

我猜这在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);
    }
}

我收到此错误:

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

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

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

不是标准,但在 cpp 首选项时明确写过,运算符[]=->()必须是非静态成员函数。

如果你能做到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的免费调用。

你可以有一个包装类和函数:

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;

现场示例您可能需要此帮助程序函数直接编写:

foo_wrapper( f )[2] = 0; 

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