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