with C ++ 14, we are allowed to compare the elements of some associative containers (for example, std :: set) with other types than those stored in the container. It should work when the comparator has is_transparent denoted as type (see, for example, std :: set :: find ).
Suppose I have a string wrapper that performs some string checks (if its format is a valid format, etc. - not very important, but building it is heavy enough that I would like to avoid it), it can throw exceptions) , and it is stored in std :: set to have a container with unique values. How do I write a comparator for this? Should it look like below? Can I overload and use my sw::operator<() to achieve the same?
class sw { public: explicit sw(const std::string& s) : s_(s) { } const std::string& getString() const { return s_; } bool operator<(const sw& other) const { return s_ < other.s_; } private: std::string s_; }; struct Comparator { using is_transparent = std::true_type; bool operator()(const sw& lhs, const std::string& rhs) const { return lhs.getString() < rhs; } bool operator()(const std::string& lhs, const sw& rhs) const { return lhs < rhs.getString(); } bool operator()(const sw& lhs, const sw& rhs) const { return lhs < rhs; } }; int main() { std::set<sw, Comparator> swSet{ sw{"A"}, sw{"B"}, sw{"C"} }; std::cout << std::boolalpha << (swSet.find(std::string("A")) != swSet.end()) << std::endl; }
I believe that the above code should work as expected, but when I tested it with g ++ 4.9 and clang ++ 3.6, both gave errors regarding the lack of conversion from string to key_type , as if the lines overloaded Comparator::operator() never were taken into account. Did I miss something?
c ++ c ++ 14 stdset
Michał Góral
source share