Function Templates

How Template Argument Deduction Works

Fixing "no matching function call" errors when using function templates.

Illustration representing computer hardware

Template argument deduction is the process by which the compiler determines the template arguments based on the types of the function arguments. Here's how it works:

  1. The compiler compares the types of the function arguments with the types of the function parameters in the template.
  2. If the types match exactly, the corresponding template argument is deduced.
  3. If the function argument is a reference or pointer, the compiler will try to deduce the template argument based on the referred or pointed-to type.
  4. If the function argument is a const or volatile qualifier, the compiler will attempt to deduce the template argument by removing the qualifiers.
  5. If the template has default arguments, they will be used if no corresponding function argument is provided.
  6. If the compiler cannot deduce all template arguments or if there are conflicts, a compilation error occurs.

Example:

template <typename T>
void foo(T a, T b) {
// ...
}

int main() {
  int x = 10;
  double y = 5.5;
  foo(x, x);// T is deduced as int
  foo(y, 2.3);// T is deduced as double
  
  // Compilation error - cannot deduce T
  // because the arguments have different types
  foo(x, y);
}

We can fix this by providing our template arguments, or casting our function arguments to help the compiler deduce how to instantiate the template:

foo<int, int>(x, y);
foo(int(x), int(y));

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved