sumty
0.1.0
Better sum types for C++
|
A type that can never be instantiated. More...
#include <utils.hpp>
Public Member Functions | |
constexpr | never ([[maybe_unused]] const never &other) noexcept |
constexpr | never ([[maybe_unused]] never &&other) noexcept |
constexpr never & | operator= ([[maybe_unused]] const never &rhs) noexcept |
constexpr never & | operator= ([[maybe_unused]] never &&rhs) noexcept |
template<typename T > | |
constexpr | operator T () const noexcept |
A type that can never be instantiated.
The never type is a special type that has no possible values. In isolation, it has no purpose, but it can be used with a sum type to represent an alternative that is never used. The sum types of sumty
optimize around never, using the assumption that an alternative of the type never will never be used.
The primary use case for never is as the error type for a result. A generic API might require that a function return a result, but the user's function may not have error code paths. In this case, the user could return a result<T, never>
. Since sumty optimizes around never, the result<T, never>
will have the same size as T
, and also be an empty type if T
is an empty type.
Despite there being no way to instantiate a never (without invoking undefined behavior), never is copyable and moveable. This ensure that using never as an alternative of a sum type does not make that type uncopyable or immovable.
never can also be implicitly converted to any other type. Although such a conversion should never be possible at runtime, it allows sum types with a never alternative to be converted. For example, a result<T, never>
can be implicitly converted to a result<T, my_error>
(assuming that my_error
is a valid type). Since the never error type can never be instantiated, the runtime conversion is always on the ok alternative (T
-> T
in our example).