2

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user1899020
  • 13,167
  • 21
  • 79
  • 154
  • Do you mean `std::make_pair`? It already has them. 1.0 *is* a `double` and `2` *is* an `int`. The types are deduced from the arguments. – WhozCraig Jul 13 '18 at 03:56
  • @WhozCraig I use pair. Can types be deduced for classes? I think it is for functions only. – user1899020 Jul 13 '18 at 03:58
  • 4
    See: [Class template argument deduction(since C++17) - cppreference.com](https://en.cppreference.com/w/cpp/language/class_template_argument_deduction) –  Jul 13 '18 at 03:59
  • Thanks to @NickyC for saving me the time of linking that. props! Now I see your question is less related to type deduction and more related to the context that deduction happens in. I glossed over your vs2017 reference. Nicky should post that as an answer with a brief description (unless there is a duplicate somewhere; I've not seen it if there is). – WhozCraig Jul 13 '18 at 04:02
  • You don't need this ugly `` any more. This is one of the selling points of C++17. – n. m. could be an AI Jul 13 '18 at 04:12
  • @WhozCraig Posted an answer as you suggested. I hope I have written it well. –  Jul 13 '18 at 04:27

1 Answers1

1

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: