How std::make_tuple makes the task simple to construct tuple of appropriate type?

How std::make_tuple makes the task simple to construct tuple of appropriate type?

make_tuple | Programming in C++

This is the continuation of my previous post on std::tuple. Please refer std::tuple before reading this post. Ignore if already read.

Initializing a std::tuple :
We can initialize a std::tuple by passing elements as arguments in constructor lets take an example,
std::tuple objTuple { 2, 1.28, “some text” };

User has to specify the type of arguments as template arguments in the tuple. Which is painful if the number of parameter gets an increase.


Also, there no way to add them using the auto keyword: 

Lets take an example,

auto objTuple { 2, 1.28, “some text” }; // Compile error

make_tuple :

C++ 11 provides std::make_tuple, by using which Constructs an object of the appropriate tuple type to contain the elements specified in args.


auto objTuple = std::make_tuple(2, 1.28, “some text” );

Example:

#include
#include
#include

int main()
{
  auto obj0 = std::make_tuple (11,'Text'); // tuple <  int, char >

  const int a = 0; int b[5];               // decayed types:
  auto obj1 = std::make_tuple (a,b);       // tuple < int, int* >

  auto obj2 = std::make_tuple (std::ref(a),"abc");  // tuple < const int&, const char* >  return 0;
}

Cpp continuation: Use of Lamda in C++.

External links for reference:

Cppreference Link for reference: https://en.cppreference.com/w/cpp/utility/tuple/make_tuple

Wiki Reference for Tuple:  https://en.wikipedia.org/wiki/C%2B%2B11#Tuple_types

One thought on “How std::make_tuple makes the task simple to construct tuple of appropriate type?

Leave a Reply