56. PairSum Multiple Template Parameters

#include <iostream>
using namespace std;

template<typename A, typename B>
auto pairSum(A a, B b) -> decltype(a+b) {
    return a + b;
}

int main() {
    double a, b;
    cin >> a >> b;
    cout << pairSum(a, b) << "\n";
    return 0;
}

Solution Details

  • template<typename A, typename B> lets the function accept two different types.
  • decltype(a+b) ensures the return type matches the result of the addition (e.g., int+float → float).
  • This avoids manual type casting and ensures safe math across types.
     

👉 In simple words:
 This function just adds two numbers, no matter if one is an int and the other is a float — it figures out the correct return type automatically.
 

Significance for Embedded Developers

  • In firmware, you often combine raw integer readings (e.g., ADC counts) with scaled floats (e.g., offsets, voltages).
     
  • A templated function avoids writing separate int, float, and double versions.
     
  • Example: pairSum(rawADC, calibrationOffset) works whether one is int and the other is float.
     
Loading...

Input

5 7

Expected Output

12