C++ Basics: Expand a Tuple into Function Arguments
Use apply to invoke a callable with the elements of a tuple as separate arguments.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. You need a C++20-capable compiler and standard-library development headers, with g++ on PATH, plus Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as apply-tuple-arguments-demo.cpp:
#include <functional>
#include <iostream>
#include <tuple>
int main()
{
const std::tuple<int, int> dimensions{4, 7};
const int area = std::apply([](int width, int height) { return width * height; }, dimensions);
std::cout << "area: " << area << '\n';
int retries = 2;
auto settings = std::make_tuple(std::ref(retries), 3);
std::apply([](int& value, int increment) { value += increment; }, settings);
std::cout << "retries: " << retries << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic apply-tuple-arguments-demo.cpp -o apply-tuple-arguments-demo &&
./apply-tuple-arguments-demoObserved output:
area: 28
retries: 5Read the result
The first call expands two tuple elements into width and height. The second call changes retries: make_tuple unwraps std::ref into a stored reference, and the lambda accepts that element by reference.
Apply it carefully
apply checks at compile time whether the callable accepts the expanded elements. make_tuple normally stores decayed values; std::ref requests reference behavior. Those references must not outlive their objects. Reference forwarding by apply does not force a lambda to accept references: a by-value parameter would still copy its argument.
The C++ working draft describes the relevant rules. This example uses C++20; the current working draft also includes later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- apply-tuple-arguments-demo.cpp apply-tuple-arguments-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.