Passing value safely to functions

This started with looking at sign/unsigned interfaces and how to handle range problems. Now this looks to me to handle any numeric conversion problems. Comments, and criticisms welcome. #include <boost/numeric/cast.hpp> template<typename Target> class numeric_class { public: template<typename Source>numeric_class(numeric_class<Source> &s) { value_ = boost::numeric_cast<Target>(s); } template<typename Source>numeric_class(Source s) { value_ = boost::numeric_cast<Target>(s); } numeric_class(Target s) { value_ = s; } template <typename Resultant> operator Resultant() { return boost::numeric_cast<Resultant>(value_); } operator Target() { return value; } private: Target value_; }; void Bar(numeric_class<unsigned long> ul) { // we know that value in ul is in range if we get here } numeric_class<float> Foo(numeric_class<unsigned long> ul) { // we know that value in ul is in range if we get here return numeric_class<float>(ul); } int main () { try { float f = 5.5; numeric_class<unsigned long> ul(f); char c1 = ul; // function interface converts float to unsigned long AND checks to make sure it is in range Bar(f); // function interface converts char to unsigned long AND checks to make sure it is in range // return float that is in range f = Foo(c1); // if we get here we have a valid f } catch(std::exception const &ex) { std::cerr << "EXCEPTION: " << ex.what() << "\n"; } return 0; }
participants (1)
-
Michael D. Borghardt