Skip to content

Commit

Permalink
feat(util): Add overloaded helper (#3816)
Browse files Browse the repository at this point in the history
This is useful in combination with `std::visit`. With this, you can do something like 

```cpp
  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);
```

which can be convenient.

I'm using this in #3869
  • Loading branch information
paulgessinger authored Nov 22, 2024
1 parent 6e3a9a6 commit edad4c9
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
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

0 comments on commit edad4c9

Please sign in to comment.