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.

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.

Error

But c++11 provided something else that can help us to avoid this pain i.e. std::make_tuple.

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,

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 initialised it and returned it.

So, basically std::make_tuple helps in automatic deduction of tuple types.

Complete example is as follows,

Output:

For Basic Usage of std::tuple refer this article,

C++11 : std::tuple Tutorial & Examples

 

Click Here to Subscribe for more Articles / Tutorials like this.