From eee954d396a9fd6c3de3a5c9108d48322bbeb626 Mon Sep 17 00:00:00 2001 From: Chris Thrasher Date: Thu, 25 May 2023 11:08:14 -0600 Subject: [PATCH] Add `rsl::Type` --- include/rsl/type.hpp | 24 ++++++++++++++++++++++++ tests/CMakeLists.txt | 3 ++- tests/type.cpp | 26 ++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 include/rsl/type.hpp create mode 100644 tests/type.cpp diff --git a/include/rsl/type.hpp b/include/rsl/type.hpp new file mode 100644 index 0000000..79d2251 --- /dev/null +++ b/include/rsl/type.hpp @@ -0,0 +1,24 @@ +#pragma once + +namespace rsl { + +/** @file */ + +/** + * @brief Class template for creating strong type aliases + * + * @tparam T value type + * @tparam Tag Tag type to diambiguate separate type aliases + */ +template +class Type { + T value_; + + public: + constexpr explicit Type(const T& value) : value_(value) {} + [[nodiscard]] constexpr T& get() { return value_; } + [[nodiscard]] constexpr const T& get() const { return value_; } + [[nodiscard]] constexpr explicit operator T() const { return value_; } +}; + +} // namespace rsl diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index d575a9f..5cc4d84 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -14,7 +14,8 @@ add_executable(test-rsl random.cpp static_string.cpp static_vector.cpp - try.cpp) + try.cpp + type.cpp) target_link_libraries(test-rsl PRIVATE rsl::rsl Catch2::Catch2WithMain diff --git a/tests/type.cpp b/tests/type.cpp new file mode 100644 index 0000000..5563200 --- /dev/null +++ b/tests/type.cpp @@ -0,0 +1,26 @@ +#include + +#include + +TEST_CASE("rsl::Type") { + using StrongInt = rsl::Type; // For testing constexpr support + using StrongString = rsl::Type; // For testing non-constexpr types + + SECTION("Construction") { + constexpr auto strong_int = StrongInt(42); + STATIC_CHECK(strong_int.get() == 42); + STATIC_CHECK(int{strong_int} == 42); + STATIC_CHECK(int(strong_int) == 42); + + auto const strong_string = StrongString("abcdefg"); + CHECK(strong_string.get() == "abcdefg"); + CHECK(std::string{strong_string} == "abcdefg"); + CHECK(std::string(strong_string) == "abcdefg"); + } + + SECTION("get()") { + auto strong_int = StrongInt(1337); + strong_int.get() = 100; + CHECK(strong_int.get() == 100); + } +}