I'm starting work on an Objective-C++ project, getting a feel for how the synthesis of the two languages feels before I do any heavy-duty design. I am very intrigued by how Automated Reference Counting has been integrated with C++: we get the equivalent of smart pointers for NSObjects
that handle retain/release properly in STL containers (cf. David Chisnall's article at http://www.informit.com/articles/article.aspx?p=1745876&seqNum=3).
I want to use STL map as a typesafe mapping from NSStrings
to C++ values. I can declare a mapping as
std::map<NSString*, MyType> mapping
With ARC, this mapping handles the memory management properly. But it doesn't follow NSString
value semantics properly, because it's using pointer comparisons instead of -[NSString compare:]
.
What's the best way to get an STL map to use string comparison instead of pointer comparison?
Should I try to specialize std::less<NSString*>
?
Should I declare an explicit comparator like std::map<NSString*, MyType, MyCompare>
?
Should I wrap the NSString*
keys in a smart pointer that implements operator<
?
You'd want a custom comparison object that calls NSString's compare function, something like this:
#include <functional>
#include <map>
struct CompareNSString: public std::binary_function<NSString*, NSString*, bool> {
bool operator()(NSString* lhs, NSString* rhs) const {
if (rhs != nil)
return (lhs == nil) || ([lhs compare: rhs] == NSOrderedAscending);
else
return false;
}
};
std::map<NSString*, MyType, CompareNSString> mapping;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With