Home > Software engineering >  no overloaded function found
no overloaded function found

Time:11-04

I have class KeyA that is from third party and will be the key in use. When I define a "<" operator, it complains:

error: no match foroperator<’ (operand types are ‘const KeyA’ andconst KeyA’)

some simplified code to show the issue:

#include <map>
using namespace std;

struct KeyA {  // defined in somewhere else
    int a;
};

namespace NS {
struct config {
    using Key = KeyA; // type alias
    using Table = map<Key, int>;
};

bool operator <(const config::Key& lhs, const config::Key& rhs) {
    return lhs.a <rhs.a ;
}
}

int main()
{
    using namespace NS;
    config::Table table;
    table[{1}]= 2;

    return 0;
}

What happens here? and how to solve this (no way to touch KeyA and most probably have to keep the overloaded function in NS)?

CodePudding user response:

One simple option is to just define your own comparator and supply that to the std::map template arguments instead:

struct config
{
    using Key = KeyA; // type alias

    struct KeyLess {
        bool operator ()(const Key& lhs, const Key& rhs) const {
            return lhs.a < rhs.a;
        }
    };

    using Table = map<Key, int, KeyLess>;
};

You can leave the other comparison function there if you want. I removed it, since it looks like you only defined it for the map anyway.

CodePudding user response:

You can use the following complete working program to solve your problem.

#include <map>
using namespace std;

struct KeyA {  // defined in somewhere else
    int a;
    //friend declaration
    friend bool operator <(const KeyA& lhs, const KeyA& rhs);
};
bool operator <(const KeyA& lhs, const KeyA& rhs) {
    return lhs.a <rhs.a ;
}
namespace NS {
struct config {
    using Key = KeyA; // type alias
    using Table = map<Key, int>;
};


}

int main()
{
    using namespace NS;
    config::Table table;
    table[{1}]= 2;

    return 0;
}

The output of the above program can be seen here.

  • Related