122. Compile-Time Overload Resolution

#include <cstdio>

// Overload for integer values
void logValue(int value) {
    std::printf("int=%d\n", value);
}

// Overload for floating-point values
void logValue(float value) {
    std::printf("float=%.2f\n", value);
}

int main() {
    logValue(10);      // Compile-time resolution
    logValue(2.5f);    // Compile-time resolution
    return 0;
}

Explanation & Logic Summary:

The template code initially provides only one overload of logValue.

Calling logValue(2.5f) fails because no matching function exists.

Adding a second overload with a different parameter type completes the overload set.

The compiler selects the correct function at compile time based solely on the argument type.

No runtime checks or dynamic dispatch are involved.

Firmware Relevance & Real-World Context:

In embedded firmware:

  • Diagnostic and hardware APIs often reuse function names across data types
  • Static resolution avoids runtime overhead and ambiguity
  • Compile-time binding guarantees deterministic behavior

Function overloading is the most basic and safest form of compile-time polymorphism and is foundational before advancing to templates and static polymorphism patterns.

 

 

 

 

Loading...

Input

Expected Output

int=10 float=2.50