So here is what I would like to do: I use std::pair
, but I would surely like to do the same using tuples, or indeed pretty much any kind of template. When assigning a pair variable, I need to type something like:
T1 t1;
T2 t2;
std::pair<T1,T2> X;
X = std::pair<T1,T2> (t1, t2);
Is there a way to omit the second <T1,T2>
when creating the new pair, and let the compiler guess, either using X's type (I'm obviously trying to create a pair<T1,T2>
) or t1
and t2
's types (I am building a pair with a T1
object and a T2
object, there is a chance the pair I want is of type pair<T1,T2>
) ?
Yes, but template argument deduction only works on function templates, not constructors of class templates. For this reason, the library provides a function:
X = std::make_pair(t1, t2);
In C++11, pairs and tuples can be initialised and assigned from initialiser lists:
X = {t1, t2};
or auto
can be used to automatically specify the type from the initialiser, so you don't need to specify the template arguments at all:
auto X = std::make_pair(t1, t2);