Home > Net >  How to use the global comparison operator when comparing two different structure types to resolve th
How to use the global comparison operator when comparing two different structure types to resolve th

Time:12-13

When I am trying to compare members of two different structures, getting the below errors:

error C2676: binary '==': 'main::strRGBSettings' does not define this operator or a conversion to a type acceptable to the predefined operator

error C2678: binary '==': no operator found which takes a left-hand operand of type 'const T1' (or there is no acceptable conversion)

Can someone help how to use the global comparison operator

#include <string>
#include <iostream>

int main()
{
 struct strRGBSettings
    {
        uint8_t red;
        uint8_t green;
        uint8_t blue;
    };

    struct strStandardColors
    {
        static strRGBSettings black() { return { 0x00, 0x00, 0x00 }; }
        static strRGBSettings red() { return { 0xFF, 0x00, 0x00 }; }
        static strRGBSettings blue() { return { 0x00, 0x00, 0xFF }; }
    };

    struct ColorState
    {
        strRGBSettings     RGB;
    };

    ColorState l_colorState;
    if (l_colorState.RGB == strStandardColors::red())
    {
        std::cout << "The color is of type Red " << std::endl;
    }
    return 0;
}

Thank you

CodePudding user response:

As the compiler error says, you need to define operator== for your strRGBSettings struct:

struct strRGBSettings {
    uint8_t red;
    uint8_t green;
    uint8_t blue;
    bool operator==(const strRGBSettings& stg) const {
        return stg.red == red && stg.blue == blue && stg.green == green;
    }
};

If you cannot modify the struct, define operator== as a non-member function:

bool operator==(const strRGBSettings& stg1, const strRGBSettings& stg2) const {
    return (stg1.red == stg2.red && stg1.blue == stg2.blue && stg1.green == stg2.green);
}

Note that this definition cannot go inside main, and you should at least be able to access the struct outside main.

  • Related