我是否必须为一个类重载每个运算符以使其行为像其成员变量之一?

Tre*_*key 9 c++ string class operator-overloading c++11

给定用户定义的类型,如下所示:

struct Word{
    std::string word;
    Widget widget;
};
Run Code Online (Sandbox Code Playgroud)

有没有办法让这个类的每个重载运算符表现得完全一样,就像它只是一个字符串一样?或者我必须通过以下方式实现该类:

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;
};
Run Code Online (Sandbox Code Playgroud)

确保我考虑字符串包含的每个重载操作,并将行为应用于字符串值.

aar*_*man 8

我想说你最好的选择就是使用std::rel_ops你只需要实现的方式==,<并获得所有这些功能.这是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';
}  
Run Code Online (Sandbox Code Playgroud)

如果你需要更完整版本的这种类型的东西使用 <boost/operators.hpp>