Add non-const overload of sf::Event::getIf

This commit is contained in:
Chris Thrasher 2024-12-29 10:57:13 -06:00
parent 3c084bf661
commit 796592edae
3 changed files with 30 additions and 0 deletions

View File

@ -316,6 +316,17 @@ public:
template <typename TEventSubtype> template <typename TEventSubtype>
[[nodiscard]] bool is() const; [[nodiscard]] bool is() const;
////////////////////////////////////////////////////////////
/// \brief Attempt to get specified event subtype
///
/// \tparam `TEventSubtype` Type of the desired event subtype
///
/// \return Address of current event subtype, otherwise `nullptr`
///
////////////////////////////////////////////////////////////
template <typename TEventSubtype>
[[nodiscard]] TEventSubtype* getIf();
//////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
/// \brief Attempt to get specified event subtype /// \brief Attempt to get specified event subtype
/// ///

View File

@ -58,6 +58,16 @@ bool Event::is() const
} }
////////////////////////////////////////////////////////////
template <typename TEventSubtype>
TEventSubtype* Event::getIf()
{
static_assert(isEventSubtype<TEventSubtype>, "TEventSubtype must be a subtype of sf::Event");
if constexpr (isEventSubtype<TEventSubtype>)
return std::get_if<TEventSubtype>(&m_data);
}
//////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
template <typename TEventSubtype> template <typename TEventSubtype>
const TEventSubtype* Event::getIf() const const TEventSubtype* Event::getIf() const

View File

@ -295,6 +295,15 @@ TEST_CASE("[Window] sf::Event")
CHECK(sensorChanged.value == sf::Vector3f()); CHECK(sensorChanged.value == sf::Vector3f());
} }
SECTION("getIf()")
{
sf::Event event = sf::Event::MouseMoved{{4, 2}};
auto* mouseMoved = event.getIf<sf::Event::MouseMoved>();
REQUIRE(mouseMoved);
mouseMoved->position = sf::Vector2i(6, 9);
CHECK(mouseMoved->position == sf::Vector2i(6, 9));
}
SECTION("visit()") SECTION("visit()")
{ {
CHECK(sf::Event(sf::Event::Closed{}).visit(visitor) == "Closed"); CHECK(sf::Event(sf::Event::Closed{}).visit(visitor) == "Closed");