What does narrow_cast do?
Asked Answered
O

2

9

I saw a code that used narrow_cast like this

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?

Oregano answered 29/10, 2019 at 21:54 Comment(1)
Search keywords: "narrow_cast c++", third link: isocpp.github.io/CppCoreGuidelines/CppCoreGuidelinesCameleer
B
14

narrow_cast of gsl is really a static_cast. But it is more explicit and you can later search for it. You can check the implementation 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++. You need gsl to compile and run this. You are probably missing that and that is why it is not compiling.

Brettbretz answered 29/10, 2019 at 22:19 Comment(0)
B
11

In Bjarne Stroustrup's "The C++(11) programming language" book, section "11.5 Explicit Type Conversion" you can see what it is.

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.

It makes a static cast to the destination type, then converts the result back to the original type. 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).

This construct could be in use in third-party libraries, but it doesn't belong to the C++ standard as far as I know.

Bolin answered 3/6, 2020 at 16:14 Comment(1)
I think you're thinking of gtl::narrow, not gtl::narrow_cast? The latter seems to be unchecked: github.com/microsoft/GSL/blob/main/include/gsl/narrowBroody

© 2022 - 2024 — McMap. All rights reserved.