Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 280
Trevor Hickey Avatar asked Dec 02 '13 04:12

Trevor Hickey


1 Answers

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. Here's a simple example from 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>

like image 149
aaronman Avatar answered Nov 10 '22 01:11

aaronman