开发者

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜