1

I have the following snippet of code that seems to be making use of predicates but I am unable to figure out what (elem.*predicator)() does. I tried looking for some easier to understand documentation regarding the same on the web as well as SO (closest thing I found was this) but couldn't find anything that could help me.

The code:

using TimePoint = std::chrono::time_point<std::chrono::system_clock>;

The struct OperationPointInfo is as follows:

struct OperationPointInfo {

  // The shelf in this operation point. -1 for empty.
  int shelf_id;
  bool scheduled_to_change;
  // The time point the shelf was moved into the operation point, in the format of seconds since epoch.
  TimePoint start_time;

  // Index for this operation point.
  int index;

  OperationPointInfo() {
    OperationPointInfo(-1);
  }

  OperationPointInfo(int index) : index(index) {
    shelf_id = -1;
    scheduled_to_change = false;
  }

  bool CapableForMoveOut() const {
    return shelf_id >= 0 && !scheduled_to_change;
  };

  bool CapableForMoveIn() const {
    return shelf_id < 0 && !scheduled_to_change;
  };
};

The function which has got me baffled is this one:

template<class T>
std::optional<T> ReserviorSamplingOperationPoint(const vector<T> &array, bool (T::*predicator)(void) const) {
  T selected;
  bool found = false;
  int counter = 1;
  for (const auto &elem : array) {
    if ((elem.*predicator)()) {
      selected = elem;
      found = true;
      counter++;
    }
  }
  if (found) {
    return selected;
  } else {
    return nullopt;
  }
}

Where the above function is being called:

void GenSpToOpMissions() {
    std::vector<OperationPointInfo> operation_point_info_;
    
    auto to_or_empty = ReserviorSamplingOperationPoint(operation_point_info_, &OperationPointInfo::CapableForMoveIn);

    OperationPointInfo to = to_or_empty.value();
}

Gaurav Agarwal
  • 611
  • 6
  • 18

1 Answers1

2

.* and ->* are the pointer-to-member operators.

Those are pointers that can store which method of a class to call.

See [expr.mptr.oper] in the standard or questions like Calling C++ class methods via a function pointer.

Acorn
  • 24,970
  • 5
  • 40
  • 69
  • Wait, I'm still a little confused. The `elem` here is of type `OperationPointInfo` right? There is no member of the name `predicator` in the definition of `OperationPointInfo`. Or is `predicator` a member accessible to all elements of std::vector<> ? – Gaurav Agarwal Jan 18 '21 at 11:18
  • 1
    `predicator` is the name of the variable (the pointer). When you call the function, then it is when you pass which method you want. – Acorn Jan 18 '21 at 16:53