From 35f0231fe83ebee43f60d476a41e965f79a4cfa3 Mon Sep 17 00:00:00 2001 From: Paul Gessinger Date: Wed, 9 Oct 2024 10:46:58 +0200 Subject: [PATCH 1/2] feat(util): Add `overloaded` helper This is useful in combination with `std::visit`. --- Core/include/Acts/Utilities/Helpers.hpp | 17 +++++++++++++++++ Tests/UnitTests/Core/Utilities/HelpersTests.cpp | 14 ++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/Core/include/Acts/Utilities/Helpers.hpp b/Core/include/Acts/Utilities/Helpers.hpp index 4bf9d1c89c3..c59555fd848 100644 --- a/Core/include/Acts/Utilities/Helpers.hpp +++ b/Core/include/Acts/Utilities/Helpers.hpp @@ -204,4 +204,21 @@ bool rangeContainsValue(const R& range, const T& value) { return std::ranges::find(range, value) != std::ranges::end(range); } +/// Helper struct that can turn a set of lambdas into a single entity with +/// overloaded call operator. This can be useful for example in a std::visit +/// call. +/// ```cpp +/// std::visit(overloaded{ +/// [](const int& i) { std::cout << "int: " << i << std::endl; }, +/// [](const std::string& s) { std::cout << "string: " << s << std::endl; }, +/// }, variant); +/// ``` +template +struct overloaded : Ts... { + using Ts::operator()...; +}; + +template +overloaded(Ts...) -> overloaded; + } // namespace Acts diff --git a/Tests/UnitTests/Core/Utilities/HelpersTests.cpp b/Tests/UnitTests/Core/Utilities/HelpersTests.cpp index 68f173db492..f6252b82482 100644 --- a/Tests/UnitTests/Core/Utilities/HelpersTests.cpp +++ b/Tests/UnitTests/Core/Utilities/HelpersTests.cpp @@ -297,6 +297,20 @@ BOOST_AUTO_TEST_CASE(incidentAnglesTest) { } } +BOOST_AUTO_TEST_CASE(Overloaded) { + struct A {}; + std::variant var; + + var = 42; + + std::visit(overloaded{ + [](int) { BOOST_CHECK(true); }, + [](double) { BOOST_CHECK(false); }, + [](A) { BOOST_CHECK(false); }, + }, + var); +} + BOOST_AUTO_TEST_SUITE_END() } // namespace Acts::Test From a93a7c5196de0113d91e24b849c0b6ba6ed9f298 Mon Sep 17 00:00:00 2001 From: Paul Gessinger Date: Wed, 6 Nov 2024 18:07:23 +0100 Subject: [PATCH 2/2] fix missing include --- Tests/UnitTests/Core/Utilities/HelpersTests.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Tests/UnitTests/Core/Utilities/HelpersTests.cpp b/Tests/UnitTests/Core/Utilities/HelpersTests.cpp index f6252b82482..aa5e011669d 100644 --- a/Tests/UnitTests/Core/Utilities/HelpersTests.cpp +++ b/Tests/UnitTests/Core/Utilities/HelpersTests.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include using namespace Acts::VectorHelpers;