窄集(_cast)的作用是什么

What does narrow_cast do?

本文关键字:作用 是什么 cast 窄集      更新时间:2023-10-16

我看到一个使用narrow_cast的代码,就像这个

int num = narrow_cast<int>(26.72);
cout << num;

问题是我的编译器说:

'narrow_cast' was not decleared in this scope. 

我是应该自己定义narrow_cast,还是我用错了方法,或者没有什么比narrow_cast更好的了?

gsl的narrow_cast实际上是static_cast。但它更明确,你可以稍后搜索。你可以自己检查实现:

// narrow_cast(): a searchable way to do narrowing casts of values
template <class T, class U>
GSL_SUPPRESS(type.1) // NO-FORMAT: attribute
constexpr T narrow_cast(U&& u) noexcept
{
return static_cast<T>(std::forward<U>(u));
}

narrow_cast不是标准C++的一部分。您需要gsl来编译和运行它。您可能遗漏了这一点,这就是为什么它没有进行编译。

在Bjarne Stroustrup的";C++(11(编程语言";书,章节";11.5显式类型转换";你可以看到它是什么。

基本上,它是一个自制的显式模板化转换函数,在这种情况下,当值可以缩小并抛出异常时使用,而static_cast不会抛出异常。

它对目标类型进行静态转换,然后将结果转换回原始类型。如果你得到相同的值,那么结果是可以的。否则,就不可能得到原始结果,因此值被缩小了,失去了信息。

你也可以看到一些例子(第298和299页(。

这个构造可以在第三方库中使用,但据我所知,它不属于C++标准。