What does narrow_cast do?

9.4k Views Asked by At

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?

2

There are 2 best solutions below

0
On

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.

1
On

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.