本文主要是介绍C++安全的窄转换narrow_cast的新语法实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//利用了C++新语法:构造自动推导模板类型
template<typename SOURCE, typename = std::enable_if_t<std::is_arithmetic<SOURCE>::value>>
struct narrow_cast
{
SOURCE source;
narrow_cast(SOURCE s) : source(s){}
template<typename TARGET, typename = std::enable_if_t<std::is_arithmetic<TARGET>::value>>
operator TARGET()
{
auto target = static_cast<TARGET>(source);
if (static_cast<SOURCE>(target) != source)
{
throw std::runtime_error("narrow_cast failed from " + to_string(source));
}
return target;
}
};
int main(int argc, char *argv[])
{
int i = 1;
long long int j = 1ll << 34;
i = narrow_cast(j);
cout << i;
cout << "Press the enter key to continue ...";
cin.get();
return EXIT_SUCCESS;
}
这篇关于C++安全的窄转换narrow_cast的新语法实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!