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

Feature Request: Allow Functor to Return bool for Early Termination of Loops #19

Open
hmojtaba opened this issue Dec 11, 2024 · 0 comments

Comments

@hmojtaba
Copy link

Update Functor to return bool instead of void to allow early termination of loops when a condition is met. If the functor returns false, the iteration stops.

Enables breaking out of loops early, improving efficiency.
Simplifies use cases like finding the first matching index.
Example

hector_math::iterateRectangle(a, b, c, row_min, row_max, col_min, col_max,
  [](Eigen::Index x, Eigen::Index y) -> bool {
    if (condition(x, y)) return false; // Stop iteration
    return true; // Continue iteration
  });

to ensure backward compatibility, perhaps sth like (c++11) (if we can use c++17 then result_of is deprecated and code needs revision):

#include <type_traits>

// Check if the functor returns bool
template<typename Functor>
constexpr bool is_functor_bool_return =
    std::is_same<typename std::result_of<Functor(Eigen::Index, Eigen::Index)>::type, bool>::value;

template<typename Functor>
inline bool callFunctor(Functor &functor, Eigen::Index x, Eigen::Index y, std::true_type /* is_bool */) {
  return functor(x, y); // Return the result for bool functor
}

template<typename Functor>
inline bool callFunctor(Functor &functor, Eigen::Index x, Eigen::Index y, std::false_type /* is_void */) {
  functor(x, y); // Ignore return value for void functor
  return true; // Always continue
}

template<typename T, typename Functor>
void iterateRectangle(const Vector2<T> &a, const Vector2<T> &b, const Vector2<T> &c,
                      Eigen::Index row_min, Eigen::Index row_max,
                      Eigen::Index col_min, Eigen::Index col_max, Functor functor) {
  bool continue_iteration = true;
  for (Eigen::Index y = col_min; y < col_max && continue_iteration; ++y) {
    for (Eigen::Index x = row_min; x < row_max && continue_iteration; ++x) {
      continue_iteration = callFunctor(functor, x, y, std::bool_constant<is_functor_bool_return<Functor>>{});
    }
  }
}

this is a compile-time functor selection and should have the same performance as before.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant