开发者

Cast int to enum

开发者 https://www.devze.com 2023-04-10 14:09 出处:网络
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

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

精彩评论

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

关注公众号