是否有一种方法可以打开数字值而不考虑类型?为了前夫。对int
进行装箱,然后取消对double
或long long
的装箱(如果转换是可能的)。关键是,如果转换是可能的,则可以将未知类型解压缩为已知类型。
现在它的表现如下:
winrt::Windows::Foundation::IInspectable boxed_value = winrt::box_value(30);
int i = winrt::unbox_value<int>(boxed_value); //OK
double d = winrt::unbox_value<double>(boxed_value); //Exception
我想要这样的东西:
winrt::Windows::Foundation::IInspectable boxed_value = winrt::box_value(30);
int i = unbox_value_with_conversion<int>(boxed_value); //OK
double d = unbox_value_with_conversion<double>(boxed_value); //OK
发布于 2020-09-10 07:02:55
如果您不知道(或者不关心)哪种类型的值已经装箱,那么使用IReference<T>
就不好玩了。链接一组unbox_value/unbox_value_or
调用将引发一系列QueryInterface
调用,这是一种非常低效率的方法。更好的做法是使用IPropertyValue。它已经执行标量转换,并处理溢出之类的错误。
winrt::Windows::Foundation::IInspectable boxed_value = winrt::box_value(30);
int i = boxed_value.as<winrt::Windows::Foundation::IPropertyValue>().GetInt32();
double d = boxed_value.as<winrt::Windows::Foundation::IPropertyValue>().GetDouble();
如果您愿意,这应该是一个简单的练习(如果有点重复/乏味),为您的unbox_value_with_conversion
提供模板专门化。
template <typename T>
T unbox_value_with_conversion(winrt::Windows::Foundation::IInspectable const& value)
{
return winrt::unbox_value<T>(value);
}
template <>
int32_t unbox_value_with_conversion<int32_t>(winrt::Windows::Foundation::IInspectable const& value)
{
return value.as<winrt::Windows::Foundation::IPropertyValue>().GetInt32();
}
// Rest of specializations...
发布于 2020-09-10 05:35:48
要实现一种无论类型如何打开数值的方法,您可以尝试将自动类型转换包装到unbox_value_with_conversion方法中,并以您提到的int、double和long long类型为例。
函数声明
template<class T>
T unbox_value_with_conversion(winrt::Windows::Foundation::IInspectable const& value);
函数定义
template<class T>
inline T MainPage::unbox_value_with_conversion(winrt::Windows::Foundation::IInspectable const& value)
{
T res{};
auto vv = value.as<winrt::Windows::Foundation::IPropertyValue>();
if (vv.Type() == winrt::Windows::Foundation::PropertyType::Int32)
{
int32_t tt = vv.as<int32_t>();
res = (T)tt;
return res;
}
if (vv.Type() == winrt::Windows::Foundation::PropertyType::Double)
{
double dd = vv.as<double>();
res = (T)dd;
return res;
}
if (vv.Type() == winrt::Windows::Foundation::PropertyType::Int64)
{
long long llong = vv.as<long long>();
res = (T)llong;
return res;
}
return T();
}
型转换
winrt::Windows::Foundation::IInspectable boxed_value1 = winrt::box_value(30);
double dd1 = unbox_value_with_conversion<double>(boxed_value1);
long long llong1= unbox_value_with_conversion<long long>(boxed_value1);
https://stackoverflow.com/questions/63812908
复制相似问题