c++ - 编写下标非成员函数

标签 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 :

error: int& operator[](foo&, std::size_t) must be a nonstatic member function

最佳答案

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 的免费调用。

关于c++ - 编写下标非成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56600576/

相关文章:

c++ - 私有(private)成员(member)和免费功能的 Doxygen 评论?

c# - 从 C++ 到 C# 的回调

c++ - 链接器如何决定使用哪个实现

java - java中运算符的定义

c# - 隐式转换运算符和相等运算符

C++运算符==和隐式转换解析

c++ - Effective C++ Item 23 Prefer non-member non-friend functions to member functions

c++为函数表建立一个名称,函数具有不同的签名

c++ - clang++: 标准头文件中的错误

c++ - 在运算符查找中,成员不会优先于非成员