Skip to content

Commit

Permalink
Add strong type macro
Browse files Browse the repository at this point in the history
  • Loading branch information
albin-johansson committed Nov 9, 2023
1 parent ec418d3 commit 022a7a3
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
17 changes: 17 additions & 0 deletions modules/core/inc/tactile/core/misc/strong_type.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Copyright (C) 2023 Albin Johansson (GNU General Public License v3.0)

#pragma once

#include <compare> // strong_ordering

/**
* \brief Simple macro useful for defining simple (but effective) strong types.
*/
#define TACTILE_STRONG_TYPE(Name, UnderlyingType) \
struct Name final { \
UnderlyingType value; \
\
constexpr auto operator==(const Name&) const noexcept -> bool = default; \
constexpr auto operator<=>(const Name&) const noexcept \
-> std::strong_ordering = default; \
}
43 changes: 43 additions & 0 deletions modules/core/test/misc/strong_type_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright (C) 2023 Albin Johansson (GNU General Public License v3.0)

#include "tactile/core/misc/strong_type.hpp"

#include <gtest/gtest.h>

#include "tactile/core/container/string.hpp"

namespace {

TACTILE_STRONG_TYPE(StrongInt, int);
TACTILE_STRONG_TYPE(StrongStr, tactile::String);

} // namespace

TEST(StrongType, DefaultValue)
{
const StrongInt integer {};
const StrongStr string {};

EXPECT_EQ(integer.value, 0);
EXPECT_EQ(string.value, "");
}

TEST(StrongType, EqualityComparison)
{
const StrongStr s1 {"foo"};
const StrongStr s2 {"bar"};

EXPECT_EQ(s1, s1);
EXPECT_EQ(s2, s2);
EXPECT_NE(s1, s2);
}

TEST(StrongType, SpaceshipComparison)
{
const StrongInt i1 {-413};
const StrongInt i2 {382};

EXPECT_EQ(i1 <=> i1, std::strong_ordering::equal);
EXPECT_EQ(i1 <=> i2, std::strong_ordering::less);
EXPECT_EQ(i2 <=> i1, std::strong_ordering::greater);
}

0 comments on commit 022a7a3

Please sign in to comment.