Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(util): Add overloaded helper #3816

Merged
merged 5 commits into from
Nov 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions Core/include/Acts/Utilities/Helpers.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 <class... Ts>
struct overloaded : Ts... {
using Ts::operator()...;
};

template <class... Ts>
overloaded(Ts...) -> overloaded<Ts...>;

} // namespace Acts
15 changes: 15 additions & 0 deletions Tests/UnitTests/Core/Utilities/HelpersTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
#include <string>
#include <tuple>
#include <utility>
#include <variant>
#include <vector>

using namespace Acts::VectorHelpers;
Expand Down Expand Up @@ -310,6 +311,20 @@ BOOST_AUTO_TEST_CASE(incidentAnglesTest) {
}
}

BOOST_AUTO_TEST_CASE(Overloaded) {
struct A {};
std::variant<int, double, A> 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
Loading