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 85e8454d052..67064306967 100644 --- a/Tests/UnitTests/Core/Utilities/HelpersTests.cpp +++ b/Tests/UnitTests/Core/Utilities/HelpersTests.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include using namespace Acts::VectorHelpers; @@ -310,6 +311,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