template struct utils::StrongType

Overview

Template class implementation of a Named Strong Type. More…

#include <StrongType.h>

template <typename ValueType, typename PhantomType>
struct StrongType {
    // construction

    StrongType();
    StrongType(ValueType value);

    // methods

    template <typename RT>
    std::enable_if_t<std::is_arithmetic_v<RT>, RT> As() const;

    bool operator==(const StrongType& other) const;
    bool operator!=(const StrongType& other) const;
    bool operator<(const StrongType& other) const;
    bool operator>(const StrongType& other) const;
    const ValueType& operator*() const;

protected:
    // fields

    ValueType value_;
};

Detailed Documentation

Template class implementation of a Named Strong Type.

https://www.fluentcpp.com/2016/12/08/strong-types-for-strong-interfaces/ “A strong type is a type used in place of another type to carry specific meaning through its name. As opposed to strong types would be general-use types, like native types such as ints and double for example. Often, native types do not tell much about the meaning of their instances.” It prevents implicit conversions to and from other types, as well as comparisons to other types.

Parameters:

ValueType

The type of the underlying value.

PhantomType

An unused type specific for each Strong Type to ensure the Strong Type is different from every other type.

Fields

ValueType value_

The actual underlying value.

Methods

template <typename RT>
std::enable_if_t<std::is_arithmetic_v<RT>, RT> As() const

Cast to a specified type. Only work for arithmetic types.

const ValueType& operator*() const

Get underlying value using the * operator.