Class strong_typedef

Synopsis

#include <include/type_safe/strong_typedef.hpp>

template <class Tag, typename T>
class strong_typedef

Description

A strong typedef emulation.

Unlike regular typedefs, this does create a new type and only allows explicit conversion from the underlying one. The Tag is used to differentiate between different strong typedefs to the same type. It is designed to be used as a base class and does not provide any operations by itself. Use the types in the strong_typedef_op namespace to generate operations and/or your own member functions.

Example:

struct my_handle
: strong_typedef<my_handle, void*>,
  strong_typedef_op::equality_comparison<my_handle>
{
    using strong_typedef::strong_typedef;
};

struct my_int
: strong_typedef<my_int, int>,
  strong_typedef_op::integer_arithmetic<my_int>,
  strong_typedef_op::equality_comparison<my_int>,
  strong_typedef_op::relational_comparison<my_int>
{
    using strong_typedef::strong_typedef;
};

Mentioned in

Methods

strong_typedef overload\effects Value initializes the underlying value.
strong_typedef overload\effects Copy (1)/moves (2) the underlying value
strong_typedef overload\group value_ctor
operator const T &\group value_conv
operator T&Returns: A reference to the stored underlying value

Source

Lines 44-96 in include/type_safe/strong_typedef.hpp.

template <class Tag, typename T>
class strong_typedef
{
public:
    /// \effects Value initializes the underlying value.
    constexpr strong_typedef() : value_() {}

    /// \effects Copy (1)/moves (2) the underlying value.
    /// \group value_ctor
    explicit constexpr strong_typedef(const T& value) : value_(value) {}

    /// \group value_ctor
    explicit constexpr strong_typedef(T&& value) noexcept(
        std::is_nothrow_move_constructible<T>::value)
    : value_(static_cast<T&&>(value)) // std::move() might not be constexpr
    {}

    /// \returns A reference to the stored underlying value.
    /// \group value_conv
    explicit TYPE_SAFE_CONSTEXPR14 operator T&() TYPE_SAFE_LVALUE_REF noexcept
    {
        return value_;
    }

    /// \group value_conv
    explicit constexpr operator const T&() const TYPE_SAFE_LVALUE_REF noexcept
    {
        return value_;
    }

#if TYPE_SAFE_USE_REF_QUALIFIERS
    /// \group value_conv
    explicit TYPE_SAFE_CONSTEXPR14 operator T &&() && noexcept
    {
        return std::move(value_);
    }

    /// \group value_conv
    explicit constexpr operator const T &&() const&& noexcept
    {
        return std::move(value_);
    }
#endif

    friend void swap(strong_typedef& a, strong_typedef& b) noexcept
    {
        using std::swap;
        swap(static_cast<T&>(a), static_cast<T&>(b));
    }

private:
    T value_;
};





Add Discussion as Guest

Log in