Type Deduction and Explicit Type Specification

You will learn about type deduction and explicit type specification in this lesson.

We'll cover the following

Type deduction

The compiler’s decision on what type to use for a template parameter is called type deduction.

Continuing from the example in the previous lesson, you may recognize that in syntax from to!string, which we have been using in earlier, the compiler decides on the following types according to the two uses of the function template:

  • int and wchar when 42 is printed
  • double and string when 1.2 is printed

The compiler can only deduce types from the types of the parameter values that are passed to function templates. Although the compiler can usually deduce the types without any ambiguity, there are times when the types must be specified explicitly by the programmer.

Explicit type specification

Sometimes it is not possible for the compiler to deduce the template parameters. A situation that this can happen is when the types do not appear in the function parameter list. When template parameters are not related to function parameters, the compiler cannot deduce the template parameter types.

Get hands-on with 1200+ tech skills courses.