编写下标非成员函数
Writing a subscript non-member function
我猜这在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(
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法