diff --git a/Bigfoot/Libs/Utils/Include/Utils/LazyGlobal.hpp b/Bigfoot/Libs/Utils/Include/Utils/LazyGlobal.hpp new file mode 100644 index 0000000..7d59dd5 --- /dev/null +++ b/Bigfoot/Libs/Utils/Include/Utils/LazyGlobal.hpp @@ -0,0 +1,40 @@ +/********************************************************************* + * \file LazyGlobal.hpp + * + * \author Romain BOULLARD + * \date September 2026 + *********************************************************************/ +#ifndef BIGFOOT_UTILS_LAZYGLOBAL_HPP +#define BIGFOOT_UTILS_LAZYGLOBAL_HPP +#include + +namespace Bigfoot +{ +template + requires std::is_default_constructible_v +class LazyGlobal +{ + public: + [[nodiscard]] + TYPE* operator->() const + { + return &Get(); + } + + [[nodiscard]] + operator TYPE*() const + { + return &Get(); + } + + private: + [[nodiscard]] + static TYPE& Get() + { + static TYPE instance; + return instance; + } +}; +} // namespace Bigfoot + +#endif diff --git a/Bigfoot/Tests/Utils/LazyGlobal.cpp b/Bigfoot/Tests/Utils/LazyGlobal.cpp new file mode 100644 index 0000000..bc5848b --- /dev/null +++ b/Bigfoot/Tests/Utils/LazyGlobal.cpp @@ -0,0 +1,72 @@ +/********************************************************************* + * \file LazyGlobal.cpp + * + * \author Romain BOULLARD + * \date September 2026 + *********************************************************************/ +#include + +#include + +#include + +namespace Bigfoot +{ +class DummyValue +{ + public: + [[nodiscard]] + std::uint32_t GetValue() const + { + return m_value; + } + + void SetValue(const std::uint32_t p_value) + { + m_value = p_value; + } + + private: + std::uint32_t m_value = 0; +}; + +/****************************************************************************************/ + +class LazyGlobalFixture: public ::testing::Test +{ + protected: +}; + +LazyGlobal g_dummyValueA; +LazyGlobal g_dummyValueB; + +/****************************************************************************************/ + +TEST_F(LazyGlobalFixture, ArrowOperator) +{ + g_dummyValueA->SetValue(42); + + EXPECT_EQ(g_dummyValueA->GetValue(), 42); +} + +/****************************************************************************************/ + +TEST_F(LazyGlobalFixture, PointerConversion) +{ + DummyValue* const pointer = g_dummyValueA; + pointer->SetValue(7); + + EXPECT_EQ(g_dummyValueA->GetValue(), 7); +} + +/****************************************************************************************/ + +TEST_F(LazyGlobalFixture, DifferentTags_ShouldYieldIndependentInstancesOfTheSameType) +{ + g_dummyValueA->SetValue(1); + g_dummyValueB->SetValue(2); + + EXPECT_EQ(g_dummyValueA->GetValue(), 1); + EXPECT_EQ(g_dummyValueB->GetValue(), 2); +} +} // namespace Bigfoot