Namespaces
Variants
Views
Actions

std::make_from_tuple

From cppreference.com
< cpp‎ | utility
 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
make_from_tuple
(C++17)

Elementary string conversions
(C++17)
(C++17)
Stacktrace
 
Defined in header <tuple>
template <class T, class Tuple>
constexpr T make_from_tuple(Tuple&& t);
(since C++17)

Construct an object of type T, using the elements of the tuple t as the arguments to the constructor.

Contents

[edit] Parameters

t - tuple whose elements to be used as arguments to the constructor of T

[edit] Return value

The constructed T object.

[edit] Notes

The tuple need not be std::tuple, and instead may be anything that supports std::get and std::tuple_size; in particular, std::array and std::pair may be used.

Due to guaranteed copy elision, T need not be movable.

[edit] Possible implementation

namespace detail {
template <class T, class Tuple, std::size_t... I>
constexpr T make_from_tuple_impl( Tuple&& t, std::index_sequence<I...> )
{
    static_assert(std::is_constructible_v<T,
        decltype(std::get<I>(std::declval<Tuple>()))...>);
    return T(std::get<I>(std::forward<Tuple>(t))...);
}
} // namespace detail
 
template <class T, class Tuple>
constexpr T make_from_tuple( Tuple&& t )
{
    return detail::make_from_tuple_impl<T>(std::forward<Tuple>(t),
        std::make_index_sequence<std::tuple_size_v<std::remove_reference_t<Tuple>>>{});
}

[edit] Example

#include <iostream>
#include <tuple>
 
struct Foo {
    Foo(int first, float second, int third) {
        std::cout << first << ", " << second << ", " << third << "\n";
    }
};
 
int main()
{
   auto tuple = std::make_tuple(42, 3.14f, 0);
   std::make_from_tuple<Foo>(std::move(tuple));
}

Output:

42, 3.14, 0

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 3528 C++17 cast containing reinterpret_cast etc. was allowed in the case of 1-tuple disallowed

[edit] See also

creates a tuple object of the type defined by the argument types
(function template) [edit]
creates a tuple of forwarding references
(function template) [edit]
(C++17)
calls a function with a tuple of arguments
(function template) [edit]