skip to content

In C++17, how does std::apply call a function with a tuple's elements, and why does passing an overloaded function name fail?

level: middleimportance: should knowfreq 35%

answer

  1. unpack, then invoke
  2. an index sequence over tuple_size
  3. get<I> for every I
  4. an overload set has no single type
  5. wrap it in a lambda

basics

~20 s

std::apply(f, t) calls f with get<0>(t), get<1>(t) and so on, expanded from an index sequence. An overloaded function name has no single type, so apply's callable parameter cannot be deduced; wrap the call in a lambda.

solid answer

~40 s

`std::apply(f, t)`, added in C++17, behaves like `std::invoke(f, std::get<0>(t), ..., std::get<N-1>(t))`, where `N` is `std::tuple_size_v` of the tuple; the library expands the calls with a `std::make_index_sequence`. The tuple is forwarded, so `std::apply(f, std::move(t))` moves the elements out. It works for `std::tuple`, `std::pair` and `std::array`, and since C++23 the standard constrains it to those tuple-like types plus `std::ranges::subrange`. Because `f` is a deduced template parameter, an overloaded name such as `scale` has no single type to deduce, and the call fails with "no matching function for call to 'apply'". The fix is a lambda, `[](auto x) { return scale(x); }`, which defers overload resolution to the call inside. The companion `std::make_from_tuple<T>(t)` passes the elements to `T`'s constructor instead.

code

cpp · 27 lines
cpp
#include <array>
#include <iostream>
#include <string>
#include <tuple>
#include <utility>

std::string describe(int status, const std::string& payload, double latencyMs) {
    return std::to_string(status) + ' ' + payload + ' ' + std::to_string(latencyMs);
}

struct Endpoint {
    std::string host;
    int port;
    Endpoint(std::string h, int p) : host(std::move(h)), port(p) {}
};

int main() {
    auto args = std::make_tuple(200, std::string("body"), 12.5);
    std::cout << std::apply(describe, args) << '\n';          // describe(200, "body", 12.5)

    int total = std::apply([](auto... xs) { return (xs + ...); },
                           std::array{1, 2, 3});              // array is tuple-like
    std::cout << total << '\n';                               // 6

    auto ep = std::make_from_tuple<Endpoint>(std::make_pair("db.local", 5432));
    std::cout << ep.host << ':' << ep.port << '\n';
}

go deeper

for a junior

Recall that std::apply calls a function with a tuple's elements as separate arguments.

for a middle

Explain the index-sequence expansion, the forwarding of the tuple's value category, and why an overload set cannot be deduced.

for a senior

Show how you would use apply in a deferred-call queue without dangling references, and when a lambda wrapper is needed.

for a principal

Judge when tuple-based argument plumbing belongs in a library interface and when a named parameter struct serves its callers better.

## What std::apply does `std::apply` (C++17, header `<tuple>`) solves a specific problem: you hold arguments in a tuple and want to call a function as if they had been written out separately. Its specification is short. Given a callable `f` and a tuple-like object `t` with `N` elements, `std::apply(f, t)` is equivalent to ```cpp std::invoke(std::forward<F>(f), std::get<0>(std::forward<Tuple>(t)), /* ... */ std::get<N - 1>(std::forward<Tuple>(t))); ``` The library builds the list of indices with `std::make_index_sequence<std::tuple_size_v<std::remove_reference_t<Tuple>>>` and expands `std::get<I>(...)` over it. Three details follow from that definition: - **`std::invoke` semantics.** `f` may be a function, a lambda, a function object, or a pointer to member; with a pointer to member, the first tuple element supplies the object. - **Value categories are forwarded.** Passing an lvalue tuple hands the function lvalue references to the elements; `std::apply(f, std::move(t))` hands it rvalue references, so a `std::string` element can be moved out. - **The return value is returned unchanged.** `apply` returns whatever `f` returns, including a reference. ## Which tuples it accepts | Argument | Accepted | Notes | |---|---|---| | `std::tuple<...>` | yes | the main use | | `std::pair<A, B>` | yes | two arguments | | `std::array<T, N>` | yes | `N` arguments of the same type | | `std::ranges::subrange` | yes, C++23 | its iterator and sentinel | | a user struct | no | it is not tuple-like in the C++23 sense | C++23 (paper P2165) constrains `apply` and `make_from_tuple` with an exposition-only concept *tuple-like*, which the standard defines as a specialization of `array`, `pair`, `tuple` or `ranges::subrange`; C++26 adds `complex`. libstdc++ applies that constraint in C++23 mode. libc++ declares `apply` without it, but its implementation calls `std::get` by qualified name, so a user type that specializes `std::tuple_size` and provides its own `get` still fails there, with "no matching function for call to 'get'". Pass one of the listed types. C++23 also gave `apply` a conditional `noexcept`. ## Why an overloaded name fails `apply`'s first parameter is a **forwarding reference to a deduced type `F`**. Template argument deduction needs one type, but a name like `scale` that refers to two overloads, `scale(int)` and `scale(double)`, is an **overload set**, not a single function. The compiler cannot pick one, because the tuple's element types are not considered when deducing `F`. Clang reports "no matching function for call to 'apply'" with the note "couldn't infer template argument '_Fn'". The same happens with a function template name such as `std::max`. The fixes, in order of preference: 1. **Wrap the call in a lambda**: `std::apply([](auto x) { return scale(x); }, t)`. The lambda is one object with one type, and overload resolution happens inside it, where the argument types are known. 2. **Cast to a specific function pointer**: `static_cast<int (*)(int)>(scale)`. This works but hard-codes the signature. 3. **Name a template specialization explicitly**, for a function template. ## Common uses - **Deferred calls.** A task queue stores a callable plus its arguments in a tuple and later runs `std::apply(f, args)`. - **Visiting every element.** `std::apply([](auto&... xs) { (print(xs), ...); }, t)` runs code for each element with a fold expression; the mechanics of folds belong to the material on parameter packs. - **Constructing from a tuple.** `std::make_from_tuple<T>(t)` (C++17) calls `T`'s constructor with the elements, which is handy when a parser returns a tuple and the domain wants an object. Since C++23 it refuses to bind a reference to a temporary when the tuple has one element. ## Pitfalls worth naming - `std::apply` takes the tuple, not separate arguments; `std::apply(f, 1, 2)` does not compile. - A tuple built with `std::forward_as_tuple` holds references, so it must not outlive the arguments it refers to; store it in a variable and pass it on later, and the elements may be gone. - `apply` does not reorder or convert anything on its own: the elements are passed in index order, and normal implicit conversions apply at the call. - The number of elements must match what the callable accepts. A tuple of three elements passed to a two-parameter function fails at compile time inside the library, which tends to produce a long diagnostic pointing at the expansion rather than at your call; reading from the bottom of the instantiation stack usually finds the culprit. - A generic lambda with a parameter pack, `[](auto&&... xs) { ... }`, accepts any element count and is the usual way to write code that works for every tuple.

  • What is the difference between std::apply and std::make_from_tuple?
    `std::apply(f, t)` calls an existing callable with the elements and returns its result. `std::make_from_tuple<T>(t)` constructs a new `T` with the elements as constructor arguments, so it works for types whose constructor cannot be named as a callable. Both are C++17, both expand `std::get<I>` over an index sequence, and since C++23 both accept only tuple-like standard types.
  • How do you call a member function through std::apply?
    Pass the pointer to member as the callable and put the object first in the tuple: `std::apply(&Server::handle, std::tuple{&server, request})`. `apply` uses `std::invoke`, which treats the first argument as the object for a pointer to member. A lambda that captures the object is often clearer.

  • std::apply calls the function once per tuple element
  • std::apply passes the tuple itself as a single argument
  • an overloaded function name works with apply because the tuple fixes the types
  • std::apply always copies the elements, even from an rvalue tuple
  • any struct can be passed to std::apply in C++23

Assumes C++17 for std::apply and std::make_from_tuple; C++23 constrains both to tuple-like standard types and adds a conditional noexcept to apply.