What is the reason for `std::make_tuple`?

JojOatXGME picture JojOatXGME · Dec 9, 2015 · Viewed 10.9k times · Source

I mean why does std::make_tuple exist? I know that there are situations where the function reduces the amount of characters you have to type because you can avoid template parameters. But is it the only reason? What makes std::tuple special that the function exists while other class templates haven't such function? Is it only because you may use std::tuple more often in such situations?


Here are two examples where std::make_tuple reduces the amount of characters:

// Avoiding template parameters in definition of variable.
// Consider that template parameters can be very long sometimes.
std::tuple<int, double> t(0, 0.0); // without std::make_tuple
auto t = std::make_tuple(0, 0.0);  // with std::make_tuple

// Avoiding template parameters at construction.
f(std::tuple<int, double>(0, 0.0)); // without std::make_tuple
f(std::make_tuple(0, 0.0));         // with std::make_tuple

But like written above, you don't have a function like this for many other class templates.

Answer

luk32 picture luk32 · Dec 9, 2015

Because you cannot use argument deduction for constructors. You need to write explicitly std::tuple<int, double>(i,d);.

It makes it more convenient for creating a tuple and passing it to another function in one-shot.

takes_tuple(make_tuple(i,d)) vs takes_tuple(tuple<int,double>(i,d)).

One less place to change when the type of i or d changes, especially if there were possible conversions to between the old and new types.

If it were possible to write std::tuple(i,d);, make_* would (probably) be redundant.

(Don't ask why here. Maybe for similar reasons why syntax A a(); does not invoke a default constructor. There are some painful c++ syntax peculiarities.)

UPDATE NOTE: As Daniel rightly notices, c++17 will be enhanced, so that template argument deduction will work for constructors, and such delegation will become obsolete.