'storing std::reference_wrapper<MyType> into std::set
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 < ⌖
}
};
// 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;
}
Solution 1:[1]
Adding a comparator is solved the problem.
std::set<std::reference_wrapper<MyType>> types;
to
std::set<std::reference_wrapper<MyType>, std::less<MyType>> types;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tugrul |
