std::experimental::apply(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– std::experimental::apply(3) πŸ’–

okay so this page is from the C++ Standard Libary manual, bestie β€” yes, that’s the manual name, and the title is literally std::experimental::apply(3). We are so back. πŸ¦‹


πŸŽ€ NAME πŸŽ€

std::experimental::apply β€” literally std::experimental::apply. That’s the whole name, no cap. πŸ’…


✨ Synopsis ✨

The synopsis is giving:

Defined in header <experimental/tuple>
template< class F, class Tuple >                   (library fundamentals TS)
constexpr decltype(auto) apply(F&& f, Tuple&& t);

It invokes the Callable object f with a tuple of arguments. That’s the vibe. 🌸


🌈 Parameters 🌈

  • f β€” the Callable object to be invoked, periodt.
  • t β€” the tuple whose elements to be used as arguments to f.

πŸ’– Return value πŸ’–

What’s returned by f. That’s it β€” whatever f gives back is the return value. 🫢


🧚 Possible implementation 🧚

Here’s the possible implementation, and yes the // Note: std::invoke is a C++17 feature line is part of the page, so don’t come for me:

namespace detail
{
    template<class F, class Tuple, std::size_t... I>
    constexpr decltype(auto) apply_impl(F&& f, Tuple&& t,
       std::index_sequence<I...>)
    {
        return std::invoke(std::forward<F>(f),
       std::get<I>(std::forward<Tuple>(t))...);
        // Note: std::invoke is a C++17 feature
    }
} // namespace detail

template<class F, class Tuple>
constexpr decltype(auto) apply(F&& f, Tuple&& t)
{
    return detail::apply_impl(std::forward<F>(f),
       std::forward<Tuple>(t),
        std::make_index_sequence<std::tuple_size_v<std::decay_t<Tuple>>>{});
}

πŸ¦‹ Example πŸ¦‹

This is the example exactly as the page gives it, including that little // Run this code comment:

// Run this code

#include <iostream>
#include <tuple>

template<typename... Ts>
void print_tuple(const std::tuple<Ts...> &tuple)
{
    std::apply([](const auto&... elem)
    {
        ((std::cout << elem << '\n'), ...);
    }, tuple);
}

int main()
{
    const std::tuple<int, char> t = std::make_tuple(5, 'a');
    print_tuple(t);
}

🌟 Output 🌟

Output is literally:

5
a

⭐ See also ⭐

  • make_tuple β€” creates a tuple object of the type defined by the argument types. Tagged (C++11) and (function template).
  • forward_as_tuple β€” creates a tuple of forwarding references. Tagged (C++11) and (function template).

πŸ’… Category πŸ’…

  • Noindexed pages

okay that’s the whole page, bestie 🫢 β€” huge cute sign-off shoutout to the footer crew: source http://cppreference.com, version/date 2024.06.10, page std::experimental::apply(3). πŸ’œβœ¨πŸŽ€

πŸ“¦ where this page comes from