问题
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>
) ?
回答1:
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);
回答2:
Yes, use std::make_pair
:
std::pair<T1,T2> X;
// some code
X = std::make_pair( t1, t2 );
Or, if you can initialize it directly:
std::pair<T1,T2> X = std::make_pair( t1, t2 ); // OR, even better:
std::pair<T1,T2> X( t1, t2 );
For C++11, initializing is even better:
auto X = std::make_pair( t1, t2 );
The assignment is the same:
X = std::make_pair( t1, t2 );
but it could also be:
X = { t1, t2 };
回答3:
std::pair<T1,T2> X = std::make_pair(t1, t2);
or with C++11
std::pair<T1, T2> X = {t1, t2};
or with C++11
auto X = std::make_pair(t1, t2);
And for std::tuple
there is std::make_tuple
.
来源:https://stackoverflow.com/questions/12192955/type-inference-when-using-templates