When is c++17 std::apply/invoke necessary for programming?

Viewed 84

As long as c++ is object-oriented programming language, I'm not sure if std::apply or std::invoke are necessary utility, which converts:

Object.Function(Args...)

into:

std::invoke(Object, Function, Args)

that looks like c-style function call. So my question is, when is this kind of scenario a necessary/convenience for daily programming? Or else, is there a case that using apply/invoke makes things simpler?

Would you help to give a good example case? Thanks a lot!

1 Answers

std::invoke enables all Callable objects to be invoked uniformly, which contains pointers to member functions and pointers to member variables that cannot be invoked with regular function call form like f(args...)

struct S {
  void f(int i);
  int x;
};

int main() {
  auto mem_vptr = &S::x;
  auto mem_fptr = &S::f;
  S s;
  std::invoke(mem_vptr, s);    // invoke like s.*mem_vptr;
  std::invoke(mem_fptr, s, 0); // invoke like (s.*mem_fptr)(0);
}
Related