Boost logo

Boost :

From: Michael D. Borghardt (michael_at_[hidden])
Date: 2004-01-03 02:41:24


Hello .

I am trying to use the numeric_cast, but I do not understand what is
happening below. Test 2 does not fail but I expect it to.

Can someone explain what is happening?

BTW I am using MVC7

#include <iostream>
#include <boost/cast.hpp>
#include <limits.h>

template<typename Target>
class numeric_class
{
public:
    template<typename Source>numeric_class(Source s)
    {
        value_ = boost::numeric_cast<Target>(s);
    };

    template<typename Resultant>void getValue(Resultant & r) { r =
boost::numeric_cast<Resultant>(value_);};
private:
    Target value_;
};

int main(int argc, char* argv[])
{
    int a;

    // I expect Test 1 to fail with a loss of range - which it does
    std::cout << "Test 1" << std::endl;
    a = 255;
    try
    {
        boost::numeric_cast<signed char>(a);
        std::cout << "Value " << a << " OK" << std::endl;
    }
    catch (boost::bad_numeric_cast &ex)
    {
        std::cout << "Value " << a << " " << ex.what() << std::endl;
    }

    // I expect Test 2 to fail with a loss of range - but it does not
    std::cout << "Test 2" << std::endl;
    a = 255;
    try
    {
        numeric_class<unsigned char> uc(a);
        std::cout << "Value " << a << " OK" << std::endl;
        signed char sc;
        uc.getValue(sc);
        a= sc;
        std::cout << "Value now signed " << a << " OK" << std::endl;
    }
    catch (boost::bad_numeric_cast &ex)
    {
        std::cout << "Value " << a << " " << ex.what() << std::endl;
    }

    // I expect Test 3 to fail with a loss of range - which it does
    std::cout << "Test 3" << std::endl;
    a = -1;
    try
    {
        numeric_class<unsigned char> uc(a);
        std::cout << "Value " << a << " OK" << std::endl;
    }
    catch (boost::bad_numeric_cast &ex)
    {
        std::cout << "Value " << a << " " << ex.what() << std::endl;
    }

    return 0;
}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk