I try this in Visual Studio c++ 2017, it works
auto a = pair(1.0, 2);
I think it should be
auto a = pair<double, int>(1.0, 2);
Why are the template not necessary here?
I try this in Visual Studio c++ 2017, it works
auto a = pair(1.0, 2);
I think it should be
auto a = pair<double, int>(1.0, 2);
Why are the template not necessary here?
It is a feature new to C++17, known as class template argument deduction. In short, this feature allows you to omit template arguments of a class template and let the compiler deduce the arguments when you declare an object of a instance of a class template.
std::pair
has a deduction guide in the standard library that looks like this:
template<class T1, class T2>
pair(T1, T2) -> pair<T1, T2>;
The expression pair(1.0, 2)
is a function-style cast expression with no explicit template argument list, which is one of several triggers of class template argument deduction.
When class template argument deduction is triggered, the compiler looks up the compiler-generated and user-written deduction guides, and discovers the deduction guide mentioned above. This deduction guide tells the compiler to deduce T1
as double
and T2
as int
bases on the constructor arguments (1.0, 2)
.
Also see: