Simplify std::invoke example.

This commit is contained in:
Anthony Calandra
2023-02-17 21:49:15 -05:00
parent 8183b4bbdb
commit 6ba2efe088
2 changed files with 20 additions and 18 deletions

View File

@@ -416,23 +416,24 @@ v; // == "trim me"
``` ```
### std::invoke ### std::invoke
Invoke a `Callable` object with parameters. Examples of `Callable` objects are `std::function` or `std::bind` where an object can be called similarly to a regular function. Invoke a `Callable` object with parameters. Examples of *callable* objects are `std::function` or lambdas; objects that can be called similarly to a regular function.
```c++ ```c++
template <typename Callable> template <typename Callable>
class Proxy { class Proxy {
Callable c; Callable c_;
public: public:
Proxy(Callable c): c(c) {} Proxy(Callable c) : c_{ std::move(c) } {}
template <class... Args>
template <typename... Args>
decltype(auto) operator()(Args&&... args) { decltype(auto) operator()(Args&&... args) {
// ... // ...
return std::invoke(c, std::forward<Args>(args)...); return std::invoke(c_, std::forward<Args>(args)...);
} }
}; };
auto add = [](int x, int y) {
return x + y; const auto add = [](int x, int y) { return x + y; };
}; Proxy p{ add };
Proxy<decltype(add)> p {add};
p(1, 2); // == 3 p(1, 2); // == 3
``` ```

View File

@@ -1085,23 +1085,24 @@ v; // == "trim me"
``` ```
### std::invoke ### std::invoke
Invoke a `Callable` object with parameters. Examples of `Callable` objects are `std::function` or `std::bind` where an object can be called similarly to a regular function. Invoke a `Callable` object with parameters. Examples of *callable* objects are `std::function` or lambdas; objects that can be called similarly to a regular function.
```c++ ```c++
template <typename Callable> template <typename Callable>
class Proxy { class Proxy {
Callable c; Callable c_;
public: public:
Proxy(Callable c): c(c) {} Proxy(Callable c) : c_{ std::move(c) } {}
template <class... Args>
template <typename... Args>
decltype(auto) operator()(Args&&... args) { decltype(auto) operator()(Args&&... args) {
// ... // ...
return std::invoke(c, std::forward<Args>(args)...); return std::invoke(c_, std::forward<Args>(args)...);
} }
}; };
auto add = [](int x, int y) {
return x + y; const auto add = [](int x, int y) { return x + y; };
}; Proxy p{ add };
Proxy<decltype(add)> p {add};
p(1, 2); // == 3 p(1, 2); // == 3
``` ```