Table of Contents

C++ Overload resolution

Overload resolution is the process where the compiler selects the best-matching function from a set of candidates. Candidates are ranked by how well their parameter types match the call's arguments: exact match beats conversion, const references beat non-const, and more specific templates beat less specific ones.

Understand overload resolution to predict which overload executes and to design APIs with clear, non-ambiguous alternatives.

Example

This example shows overload resolution choosing different functions based on argument types.

// compile: g++ -o overload overload.cpp
// run: ./overload
// description: overload resolution selects best-matching function
 
#include <iostream>
 
void process(int x) { std::cout << "process(int)\n"; }
void process(double x) { std::cout << "process(double)\n"; }
void process(const char* x) { std::cout << "process(const char*)\n"; }
 
template <typename T>
void generic(T x) { std::cout << "generic(T)\n"; }
 
template <>
void generic<int>(int x) { std::cout << "generic(int) specialized\n"; }
 
int main() {
    process(42);        // exact match: int
    process(3.14);      // exact match: double
    process("hello");   // exact match: const char*
 
    generic(42);        // matches specialized int
    generic(3.14);      // matches generic double
 
    return 0;
}