Boost logo

Boost Users :

From: Sohail Somani (s.somani_at_[hidden])
Date: 2006-03-27 12:45:48


By defn, static_cast does not provide runtime checks. You should use an
enum class or something. Boost needs scoped enums!

Anyway, I've used this with varying degrees of success but its not
really easy to specialize:

#include <cassert>

struct MyEnum
{
        enum type
        {
                a,b,c,
                min=a,
                max=c
        };
};

template<typename Enum>
typename Enum::type convert_enum(int a)
{
        typedef typename Enum::type type_;
        assert(a >= Enum::min && a <= Enum::max);
        return type_(a);
}

int main()
{
        MyEnum::type b(convert_enum<MyEnum>(0)); // ok
        MyEnum::type a(convert_enum<MyEnum>(5)); // dies
}

> -----Original Message-----
> From: boost-users-bounces_at_[hidden]
> [mailto:boost-users-bounces_at_[hidden]] On Behalf Of
> Oliver.Kowalke_at_[hidden]
> Sent: Sunday, March 26, 2006 10:42 PM
> To: boost-users_at_[hidden]
> Subject: [Boost-users] safe assign of int to enum
>
> Hello,
> is a technique available in boost in order to assign an int value to a
> enum?
>
> enum E
> {
> e1 = 1,
> e2 = 2,
> e3 = 3
> };
>
> E e( static_cast< E >( 1) ); // should work
>
> E e( static_cast< E >( 5) ); // should throw exception at runtime
>
> Regards,
> Oliver
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net