Arene Base
Fundamental Utilities For Safety Critical C++
Loading...
Searching...
No Matches
tuple: Facilities For Manipulating std::tuple

The tuple sub-package provides a facility for working with std::tuple.

The public header is

The Bazel target is

//:tuple

Working With Tuples

The tuple package provides facilities for applying invocables to the elements of a std::tuple.

Firstly, arene::base::apply invokes the supplied invocable once, with the elements of the tuple as arguments to the invocable:

void foo() {
std::tuple<int, double, std::string> values(42,3.14,"hello");
arene::base::apply([](int intvar, double dblvar, const std::string& strvar) {
std::cout<<"i= "<<intvar<<", d="<<dblvar<<", s="<<strvar<<"\n";
}, values);
}
a heterogeneous, fixed-size collection of values
Definition tuple.hpp:681

Here, the values tuple is split into separate arguments and passed to the lambda, which then prints them out.

arene::base::for_each instead invokes the invocable for each element in turn:

class do_print{
public:
void operator()(int val) const{
std::cout<<"int ="<<val<<"\n";
}
void operator()(double val) const{
std::cout<<"double ="<<val<<"\n";
}
void operator()(const std::string& val) const{
std::cout<<"string ="<<val<<"\n";
}
};
void bar() {
std::tuple<int, double, std::string> values(42,3.14,"hello");
arene::base::for_each(values, do_print{});
}
constexpr void for_each(Tuple &&tuple, Op &&operation)
Perform an operation on each element of a "tuple-ish" type, which includes std::tuple,...
Definition for_each.hpp:108

In this case, the values tuple is again split, but now into separate function calls, so the do_print invocable is invoked 3 times: once with the int element, once with the double element, and finally once with the std::string element.

Finally, arene::base::for_each_index does the same splitting as arene::base::for_each, but additionally passes the index of the element to the operation as the first argument.

void baz() {
std::tuple<std::string, std::string, std::string> values("hello","world","goodbye");
arene::base::for_each_index([](std::size_t index, const std::string& str) {
std::cout<<"val "<<index<<" = "<<str<<"\n";
});
}
constexpr void for_each_index(Tuple &&tuple, Op &&operation)
Perform an operation on each element of a "tuple-ish" type, which includes std::tuple,...
Definition for_each.hpp:143
::size_t size_t
A type suitable for holding the size of an object.
Definition cstddef.hpp:29

Here, the lambda is again called 3 times: first as lambda(0, "hello"), then as lambda(1, "world"), and finally as lambda(2, "goodbye").