[英]Do I have to overload every operator for a class to behave like one of its member variables?
Given a user defined type such as the following: 给定用户定义的类型,如下所示:
struct Word{
std::string word;
Widget widget;
};
Is there a way to make every overloaded operator of the class behave exactly the same as if it was just a string? 有没有办法让这个类的每个重载运算符表现得完全一样,就像它只是一个字符串一样? Or do I have to implement the class the following way:
或者我必须通过以下方式实现该类:
struct Word{
bool operator < (Word const& lhs) const;
bool operator > (Word const& lhs) const;
bool operator <= (Word const& lhs) const;
bool operator => (Word const& lhs) const;
bool operator == (Word const& lhs) const;
bool operator != (Word const& lhs) const;
//etc...
std::string word;
Widget widget;
};
making sure I account for every overloaded operation a string contains, and applying the behaviour to just the string value. 确保我考虑字符串包含的每个重载操作,并将行为应用于字符串值。
I would say your best option is to use std::rel_ops
that way you only have to implement ==
and <
and you get the functionality of all of them. 我想说你最好的选择是使用
std::rel_ops
,这样你只需要实现==
和<
并获得所有这些功能。 Here's a simple example from cppreference. 这是cppreference的一个简单示例。
#include <iostream>
#include <utility>
struct Foo {
int n;
};
bool operator==(const Foo& lhs, const Foo& rhs)
{
return lhs.n == rhs.n;
}
bool operator<(const Foo& lhs, const Foo& rhs)
{
return lhs.n < rhs.n;
}
int main()
{
Foo f1 = {1};
Foo f2 = {2};
using namespace std::rel_ops;
std::cout << std::boolalpha;
std::cout << "not equal? : " << (f1 != f2) << '\n';
std::cout << "greater? : " << (f1 > f2) << '\n';
std::cout << "less equal? : " << (f1 <= f2) << '\n';
std::cout << "greater equal? : " << (f1 >= f2) << '\n';
}
If you need a more complete version of this type of thing use <boost/operators.hpp>
如果您需要更完整版本的此类事物,请使用
<boost/operators.hpp>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.