Skip to content

Commit 5055ade

Browse files
committed
Update heterogeneous-lookup.cpp using a custom comparator
1 parent 9a9e357 commit 5055ade

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

Curiosity/heterogeneous-lookup.cpp

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1+
#include <cassert>
12
#include <set>
23
#include <string>
34
#include <string_view>
4-
#include <cassert>
55

66
struct Product {
77
std::string name;
@@ -20,6 +20,19 @@ bool operator<(const std::string_view &name1, const Product &p2) {
2020
return name1 < p2.name;
2121
}
2222

23+
struct MyComparator { // my custom comparator compatible with heterogeneous lookup
24+
bool operator()(const Product &p1, const Product &p2) const {
25+
return p1.name < p2.name;
26+
}
27+
bool operator()(const Product &p1, const std::string_view &name2) const {
28+
return p1.name < name2;
29+
}
30+
bool operator()(const std::string_view &name1, const Product &p2) const {
31+
return name1 < p2.name;
32+
}
33+
using is_transparent = int; // enable heterogeneous lookup
34+
};
35+
2336
int main() {
2437
std::set<Product> products1{
2538
{"Car", "This is a super car that costs a lot", 100'000.0},
@@ -30,11 +43,22 @@ int main() {
3043
// default comparator
3144

3245
std::set<Product, std::less<>> products2{
33-
// use C++14 heterogenous comparator
46+
// use C++14 heterogeneous comparator
47+
{"Car", "This is a super car that costs a lot", 100'000.0},
48+
{"Ball", "A cheap but nice-looking ball to play", 100.0},
49+
{"Orange", "Something to eat and refresh", 50.0}};
50+
51+
auto finder2 = products2.find("Car"); // Can compare Product and 'const char *'
52+
// this 'find' method is not the same
53+
// it use a template type + SFINAE
54+
// see std::less<void> + is_transparent
55+
assert(finder2 != products2.end());
56+
57+
std::set<Product, MyComparator> products3{
3458
{"Car", "This is a super car that costs a lot", 100'000.0},
3559
{"Ball", "A cheap but nice-looking ball to play", 100.0},
3660
{"Orange", "Something to eat and refresh", 50.0}};
3761

38-
auto finder = products2.find("Car"); // Cannot compare Product and 'const char *'
39-
assert(finder != products2.end());
62+
auto finder3 = products3.find("Car"); // My custom 'transparent' comparator
63+
assert(finder3 != products2.end());
4064
}

0 commit comments

Comments
 (0)