C++ Tuple::forward_as_tuple() Function



The C++ std::tuple::forward_as_tuple() function is used to construct a tuple by fowarding its arguments, preserving their original types and forwarding them as rvalue references. unlike the std::make_tuple() function, it maintains the value category of each element.

This function can be used in conjunction with functions like std::tie() and std::tuple_cat() to manipulate tuples and unpack their elements.

Syntax

Following is the syntax for std::tuple::forward_as_tuple() function.

forward_as_tuple (Types&&... args) noexcept;

Parameters

  • args − It indicates the list of elements to be forwarded as a tuple object of reference.

Example

Let's look at the following example, where we are going to use the forward_as_tuple() function to create a tuple of references to x and y and then passed to print the tuple elements.

#include <tuple>
#include <iostream>
void tp(const std::tuple<int, float>& t)
{
    std::cout << std::get<0>(t) << ", " << std::get<1>(t) << " " <<std::endl;
}
int main()
{
    int x = 2;
    float y =0.02;
    tp(std::forward_as_tuple(x, y));
    return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

2, 0.02 

Example

Consider the following example, where we are going to return the multiple values from the function.

#include <tuple>
#include <iostream>

std::tuple<float, std::string> get_values()
{
    float a = 0.01;
    std::string b = "TutorialsPoint";
    return std::forward_as_tuple(a, b);
}
int main()
{
    auto x = get_values();
    std::cout << std::get<0>(x) << ", " << std::get<1>(x) << std::endl;
    return 0;
}

Output

Following is the output of the above code −

0.01, TutorialsPoint

Example

In the following example, we are going to use the std::tie() with the forward_as_tuple() function.

#include <tuple>
#include <iostream>
int main()
{
    int x = 1;
    float y = 0.01;
    std::tie(x, y) = std::forward_as_tuple(x, y);
    std::cout << x << ", " << y << std::endl;
    return 0;
}

Output

If we run the above code it will generate the following output −

1, 0.01

Example

Following is the example, where we are going to use the forward_as_tuple() function along with std::apply().

#include <tuple>
#include <iostream>
void a(int x, const std::string& y)
{
    std::cout << x << ", " << y << std::endl;
}
int main()
{
    auto b = std::forward_as_tuple(123, "Welcome");
    std::apply(a, b);
    return 0;
}

Output

Output of the above code is as follows −

123, Welcome
Advertisements