Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does narrow_cast do?

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?

like image 498
Lekan Avatar asked Apr 15 '26 00:04

Lekan


2 Answers

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.

like image 186
Ayxan Haqverdili Avatar answered Apr 17 '26 15:04

Ayxan Haqverdili


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.

like image 31
mcrae Avatar answered Apr 17 '26 14:04

mcrae