How Template Argument Deduction Works

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

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));

Function Templates

Understand the fundamentals of C++ function templates and harness generics for more modular, adaptable code.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Common Errors with Function Templates
Help me fix compile-time errors encountered when using function templates
When to Use Function Templates
Why do we need function templates? When are they useful?
Function Templates vs Function Overloading
What is the difference between using a function template and overloading a function?
Template Specialization for Function Templates
How can my template function have different behaviour based on the template arguments?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant