In this article we will discuss what is std::make_tuple and why do we need it.
Initializing a std::tuple
We can initialize a std::tuple by passing elements as arguments in constructor i.e.
// Creating and Initializing a tuple std::tuple<int, double, std::string> result1 { 22, 19.28, "text" };
You might have observed that we need to specify type of arguments as template arguments in tuple. Sometime its painful if number of elements are more.
With this there is no way to deduce them automatically i.e. Following code will give compile error i.e.
// Compile error, as no way to deduce the types of elements in tuple auto result { 22, 19.28, "text" }; // Compile error
Error
error: unable to deduce ‘std::initializer_list<_Tp>’ from ‘{22, 1.9280000000000001e+1, "text"}’ auto result { 22, 19.28, "text" };
But c++11 provided something else that can help us to avoid this pain i.e. std::make_tuple.
Frequently Asked:
std::make_tuple
std::make_tuple creates a std::tuple object by deducing the target types of elements in tuple from the types of arguments.
Let’s understand by an example,
// Creating a tuple using std::make_tuple auto result2 = std::make_tuple( 7, 9.8, "text" );
Here we didn’t specify any type of the element encapsulated by std::tuple object result.
std::make_tuple did following things,
std::make_tuple took three arguments and automatically deduced their types as int, double and string. Then it created a std::tuple<int, double, std::string> object internally and initialized it and returned it.
// Creating a tuple using std::make_tuple auto result = std::make_tuple( 7, 9.8, "text" );
So, basically std::make_tuple helps in automatic deduction of tuple types.
Complete example is as follows,
#include <iostream> #include <tuple> #include <string> int main() { // Creating and Initializing a tuple std::tuple<int, double, std::string> result1 { 22, 19.28, "text" }; // Compile error, as no way to deduce the types of elements in tuple //auto result { 22, 19.28, "text" }; // Compile error // Creating a tuple using std::make_tuple auto result2 = std::make_tuple( 7, 9.8, "text" ); // std::make_tuple automatically deduced the type and created tuple // Print values std::cout << "int value = " << std::get < 0 > (result2) << std::endl; std::cout << "double value = " << std::get < 1 > (result2) << std::endl; std::cout << "string value = " << std::get < 2 > (result2) << std::endl; return 0; }
Output:
int value = 7 double value = 9.8 string value = text
For Basic Usage of std::tuple refer this article,
Pointers in C/C++ [Full Course]
C++11 : std::tuple Tutorial & Examples
OH! This is really helpful and easy to learn…Your writings are as if we are learning ABCDEFGH…Even a lame person can understand your lectures…Terrific.