Understanding Overload Resolution

Debugging Overload Resolution Failures

How can I debug a situation where the compiler is not selecting the overload I expect it to?

Illustration representing computer hardware

When the compiler does not select the overload you expect, it can lead to compilation errors or unexpected behavior. To debug this, you can follow these steps:

  1. Check the parameter types of the overloads and the arguments you're passing. Make sure they match or that there are valid implicit conversions.
  2. If you're using templates, verify that the deduced types are what you expect. You can use static_assert and typeid to print out the deduced types.
  3. If there are multiple viable overloads, remember that the compiler will prefer the most specific one. An exact match is better than a match requiring conversions.
  4. Check for ambiguities. If there are multiple overloads that are equally good matches, the compiler will emit an ambiguity error.
  5. Use explicit casts or template arguments to guide the compiler if necessary.

For example, consider this code:

#include <iostream>

void Print(int x) {
  std::cout << "Print(int)\n";
}

void Print(double x) {
  std::cout << "Print(double)\n";
}

int main() {
  Print(10);// calls Print(int)
  Print(10.0);// calls Print(double)

  // float converted to double
  Print(10.0f); // calls Print(double)

  // char promoted to int
  Print('a');// calls Print(int)
}
Print(int)
Print(double)
Print(double)
Print(int)

By analyzing the types of the arguments and the parameter types of the overloads, you can understand which overload will be called in each case.

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

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