mercredi 23 février 2022

storing std::reference_wrapper

I was hoping infer std::reference_wrapper<MyType> to MyType& automagically on bool operator<(. It is not matching the method. But the code is compiling when I add additional bool operator<( method. Am I missing something?

#include <iostream>
#include <set>
#include <functional>


class MyType {
public:
    bool operator<(const MyType& target) const {
        return this < &target;
    }
};

// it doesn't compile if remove the method below.
bool operator<(const std::reference_wrapper<MyType>& a, const MyType& b) {
    return a.get() < b;
}

int main(int argc, char* argv[]) {

    std::set<std::reference_wrapper<MyType>> types;

    MyType t1, t2, t3;

    types.insert(std::ref(t1));
    types.insert(std::ref(t2));
    types.insert(std::ref(t3));
    types.insert(std::ref(t1));

    std::cout << "size: " << types.size() << std::endl;

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire