5

Why do we need std::invoke, when we already have std::function? What is the difference between them? Both used to call callable objects. What's the point to add new template?

Ivan Kush
  • 2,958
  • 2
  • 23
  • 39
  • 13
    We already have a car. Why do we need the color green? (In short, in what way are those two things **similar**???) – Yakk - Adam Nevraumont Sep 08 '16 at 19:27
  • 6
    `std::invoke` and `std::function` don't do the same thing at all – David Sep 08 '16 at 19:27
  • 3
    Watch this [cppcon 2015 talk by Stephan T. Lavavej](https://www.youtube.com/watch?v=zt7ThwVfap0) – NathanOliver Sep 08 '16 at 19:28
  • 1
    @Yakk Maybe the point is that instead of holding a function pointer or member function pointer, you could hold an equivalent `std::function` and just call it directly. So why would anyone need `std::invoke`? – Tavian Barnes Sep 08 '16 at 19:29
  • That's like asking why we need `std::for_each` when we already have `std::vector`. – Kerrek SB Sep 08 '16 at 19:34
  • 2
    @TavianBarnes True, instead of painting a glass wall with green paint, you could park a car in front of it. Both would block the light. So both green and cars are opaque in the right circumstances... And if the OP only thought of one application where opacity is all they need, I guess that could be the source of the question. I still actually want a clarification from the OP. – Yakk - Adam Nevraumont Sep 08 '16 at 19:37
  • @NathanOliver, thanks! The best comment! – Ivan Kush Sep 08 '16 at 21:18
  • @David, do the same, they both used to call callable objects in the end. Only in std::function we need to add brackets in the end. – Ivan Kush Sep 08 '16 at 21:25

1 Answers1

10

std::invoke is a generic way to activate any callable - a std::function, a pointer to function, a pointer to member function, a function object etc. Without having to know which one you are dealing with (and without having to use different syntax). It's mostly useful in generic programming (templates).

A standard function on the other hand is a generic container for a callable "thing". Not at all the same..

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70