Add static_pointer_cast

The current implementation of gsl::not_null provides a constructor to
convert from not_null<U> to not_null<T> when there exists an implicit
conversion from U to T.

However it does not provide an easy way to convert from not_null<U> to
not_null<T> when the conversion from U to T requires the use of
static_cast.

Manually, one would have to do:

auto converted = gsl::not_null<T>(static_cast<T>(original.get()))

In accordance with the STL naming conventions, I propose the function
"gsl::static_pointer_cast(gsl::not_null<U> const &)" to do the job. Until
the GSL gets merged with the STL, it would lie on the ::gsl namespace,
instead of being on ::std along with
static_pointer_cast(std::shared_ptr<U> const &).

Note 1: We could add noexcept if not_null's constructor were noexcept.
Note 2: dynamic_pointer_cast should not be implemented, since dynamic_cast
can return nullptr.
This commit is contained in:
Samuel García Salas 2015-11-14 03:05:59 +01:00
parent 70e735b911
commit fcdff2f205

View File

@ -195,6 +195,8 @@ private:
not_null<T>& operator-=(size_t) = delete; not_null<T>& operator-=(size_t) = delete;
}; };
template<class T, class U> not_null<T> static_pointer_cast(not_null<U> const & ptr) { return not_null<T>{static_cast<T>(ptr.get())}; }
} // namespace gsl } // namespace gsl
namespace std namespace std