Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rsl::StrongType #87

Merged
merged 1 commit into from
Nov 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions include/rsl/strong_type.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#pragma once

#include <utility>

namespace rsl {

/** @file */

/**
* @brief Class template for creating strong type aliases
*
* @tparam T value type
* @tparam Tag Tag type to disambiguate separate type aliases
*/
template <typename T, typename Tag>
class StrongType {
T value_;

public:
/**
* @brief Construct from any type
*/
constexpr explicit StrongType(T value) : value_(std::move(value)) {}

/**
* @brief Get non-const reference to underlying value
*/
[[nodiscard]] constexpr T& get() { return value_; }

/**
* @brief Get const reference to underlying value
*/
[[nodiscard]] constexpr const T& get() const { return value_; }

/**
* @brief Explicit conversion to underlying type
*/
[[nodiscard]] constexpr explicit operator T() const { return value_; }
};

} // namespace rsl
1 change: 1 addition & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ add_executable(test-rsl
random.cpp
static_string.cpp
static_vector.cpp
strong_type.cpp
try.cpp)
target_link_libraries(test-rsl PRIVATE
rsl::rsl
Expand Down
27 changes: 27 additions & 0 deletions tests/strong_type.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#include <rsl/strong_type.hpp>

#include <catch2/catch_test_macros.hpp>

TEST_CASE("rsl::StrongType") {
using StrongInt = rsl::StrongType<int, struct StrongIntTag>; // For testing constexpr support
using StrongString =
rsl::StrongType<std::string, struct StringStringTag>; // 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);
}
}
Loading