There is a feature in Boost.LexicalCast
that allows users to use their own types with lexical_cast
. This feature requires from the user to write the correct std::ostream
and std::istream
operators for the type.
- All you need is to provide
operator<<
andoperator>>
stream operators. If your class is already streamable, nothing needs to be done:
#include <iostream> #include <stdexcept> // Negative number that does not store minus sign. class negative_number { unsigned short number_; public: explicit negative_number(unsigned short number = 0) : number_(number) {} // ... unsigned short value_without_sign() const { return number_; } }; inline std::ostream& operator<<(std::ostream& os, const negative_number& num) { os << '-' << num.value_without_sign(); return os; } inline std::istream& operator>>(std::istream&...