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;
}
}
Either use:
result = (T)Enum::ToObject(T::typeid, 0);
or the slightly "uglier":
result = (T)(Object^)0;
精彩评论