Provide additional checks for event handlers

This commit is contained in:
Pixel-Tony 2025-01-04 00:41:13 +01:00
parent 796592edae
commit 17d387cd1a
3 changed files with 16 additions and 0 deletions

View File

@ -389,6 +389,19 @@ private:
template <typename T> template <typename T>
static constexpr bool isEventSubtype = isInParameterPack<T>(decltype (&m_data)(nullptr)); static constexpr bool isEventSubtype = isInParameterPack<T>(decltype (&m_data)(nullptr));
template <typename Handler, typename... Ts>
static constexpr bool isInvokableWithAnyOf(std::variant<Ts...>*)
{
return (std::is_invocable_v<Handler, const Ts&> || ...);
}
public:
template <typename Handler>
static constexpr bool isValidHandler()
{
return isInvokableWithAnyOf<Handler>(static_cast<decltype(m_data)*>(nullptr));
}
}; };
} // namespace sf } // namespace sf

View File

@ -61,6 +61,8 @@ template <typename... Ts>
void WindowBase::handleEvents(Ts&&... handlers) // NOLINT(cppcoreguidelines-missing-std-forward) void WindowBase::handleEvents(Ts&&... handlers) // NOLINT(cppcoreguidelines-missing-std-forward)
{ {
static_assert(sizeof...(Ts) > 0, "Must provide at least one handler"); static_assert(sizeof...(Ts) > 0, "Must provide at least one handler");
static_assert((Event::isValidHandler<Ts>() && ...),
"All event handlers must accept a single parameter, either a const reference or a value");
// Disable misc-const-correctness for this line since clang-tidy // Disable misc-const-correctness for this line since clang-tidy
// complains about it even though the code would become uncompilable // complains about it even though the code would become uncompilable

View File

@ -213,6 +213,7 @@ TEST_CASE("[Window] sf::WindowBase", runDisplayTests())
// Should compile if user provides only a specific handler // Should compile if user provides only a specific handler
windowBase.handleEvents([](const sf::Event::Closed&) {}); windowBase.handleEvents([](const sf::Event::Closed&) {});
windowBase.handleEvents([](sf::Event::Closed) {});
// Should compile if user provides only a catch-all // Should compile if user provides only a catch-all
windowBase.handleEvents([](const auto&) {}); windowBase.handleEvents([](const auto&) {});