简体   繁体   English

narrow_cast 有什么作用?

[英]What does narrow_cast do?

I saw a code that used narrow_cast like this我看到一个像这样使用narrow_cast的代码

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

The problem is my compiler said:问题是我的编译器说:

'narrow_cast' was not decleared in this scope. 

Am I supposed to define narrow_cast myself or am I using it the wrong way or is there nothing like narrow_cast ?我应该自己定义narrow_cast还是我以错误的方式使用它,还是没有像narrow_cast这样的东西?

narrow_cast of gsl is really a static_cast . gsl 的narrow_cast实际上是一个static_cast But it is more explicit and you can later search for it.但它更明确,您可以稍后搜索它。 You can check theimplementation yourself:您可以自己检查实现

// 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 is not a part of the standard C++. narrow_cast不是标准 C++ 的一部分。 You need gsl to compile and run this.您需要gsl来编译和运行它。 You are probably missing that and that is why it is not compiling.您可能错过了这一点,这就是它没有编译的原因。

In Bjarne Stroustrup's "The C++(11) programming language" book, section "11.5 Explicit Type Conversion" you can see what it is.在 Bjarne Stroustrup 的“The C++(11) 编程语言”一书中的“11.5 显式类型转换”一节中,您可以看到它是什么。

Basically, it is a homemade explicit templated conversion function, used when values could be narrowed throwing an exception in this case, whereas static_cast doesn't throw one.基本上,它是一种自制的显式模板转换 function,在这种情况下可以缩小值并抛出异常时使用,而 static_cast 不会抛出异常。

It makes a static cast to the destination type, then converts the result back to the original type.它将 static 转换为目标类型,然后将结果转换回原始类型。 If you get the same value, then the result is OK.如果你得到相同的值,那么结果是好的。 Otherwise, it's not possible to get the original result, hence the value was narrowed losing information.否则,不可能得到原始结果,因此值被缩小丢失信息。

You also can see some examples of it (pages 298 and 299).您还可以看到它的一些示例(第 298 和 299 页)。

This construct could be in use in third-party libraries, but it doesn't belong to the C++ standard as far as I know.此构造可能在第三方库中使用,但据我所知,它不属于 C++ 标准。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM