窄集(_cast)的作用是什么
What does narrow_cast do?
我看到一个使用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++标准。
相关文章:
- "using namespace std;"在C++的作用是什么?
- 此代码中的" "是什么,它的基本作用是什么?
- 在模板参数中使用 {} 在 type_trait{} 中时,其作用是什么<T>?
- <<、>>算子在循环中的作用是什么
- 在c++中,减号和加号对字符串的作用是什么
- 窄集(_cast)的作用是什么
- 在这种情况下,#define 的作用是什么?
- 遍历模板参数包,没有争论的专业化的作用是什么?
- 在 c++ 中,没有 **std::fixed** 的 **std::setprecision()** 的作用是什么?
- 访问多个阵列时 CPU 缓存的作用是什么?
- 以下表达式的作用是什么:x = (a1,a2,..,n);
- 私人成员的作用是什么?
- 这段代码的作用是什么?
- *.exp文件的作用是什么
- ifstream::open()真正的作用是什么
- 如何在矩阵中使用指针.这行代码的作用是什么:int r=**(++b);
- 这个函数的作用是什么?与夹紧值有关
- 这个运算符()语法的作用是什么
- std::函数的模板参数中“const”修饰符和引用的作用是什么
- 字符串流在C++编程中的作用是什么