N_A
N_A

Reputation: 19897

Cast int to enum

I'm trying to use a generic enum type in a C++/CLI helper class and I want it to default to 0 if the cast doesn't work. My problem is that result = (T)0; doesn't work. Is there a way around this?

Error 1 error C2440: 'type cast' : cannot convert from 'int' to 'T'

generic <typename T> where T: value class, Enum
static void SetEnumPropertyValue(String^ value, [Out] T %result)
{
    if (String::IsNullOrEmpty(value))
            false;
    if (!Enum::TryParse<T>(value, true, result))
    {
        result = (T)0;
    }
}

Upvotes: 3

Views: 2434

Answers (1)

DeCaf
DeCaf

Reputation: 6086

Either use:

   result = (T)Enum::ToObject(T::typeid, 0);

or the slightly "uglier":

   result = (T)(Object^)0;

Upvotes: 3

Related Questions