dcleblanc / SafeInt

SafeInt is a class library for C++ that manages integer overflows.
MIT License
202 stars 37 forks source link

please add common STL support #43

Closed MacroUniverse closed 2 years ago

MacroUniverse commented 2 years ago

When using std::unordered_map<> with SafeInt, there's an error saying std::hash is undefined. Could you add a hash function to the namespace std ? Also, cout << doesn't seem to work ether.

dcleblanc commented 2 years ago

I could fairly easily overload operator << so that cout would work. In the meantime, just cast the SafeInt back to its type, and then cout will work.

Implementing the hashing function is pretty easy, you can just do this, since there's specializations already for all the types that SafeInt can wrap:

template struct std::hash<SafeInt> { [std::size_t] operator()(SafeInt const& s) const noexcept { return std::hash(); } };

Note - I didn't go and make sure this would work, but this appears to be the approach used when using an unordered_map with something other than the basic types.

dcleblanc commented 2 years ago

BTW, the rich text parser ate some of the code - the template can't be fully specified, as SafeInt itself is a template, so:

template &LT typename T &GT

Then you just end up returning std::hash for type T, since there's a built in specialization for all the integer types.

dcleblanc commented 2 years ago

This is now documented in helpfile.md