57. Threshold Default Template Arguments

#include <iostream>
using namespace std;

template<typename T = int> T thresholdOrDefault(T v, T def = {}) {
    if (v < 0) return def;
    return v;
}

int main() {
    int v, def;
    if (cin.peek() == '-') {
        cin >> v;
        if (cin.peek() == ' ') {
            cin >> def;
            cout << thresholdOrDefault(v, def) << "\n";
        } else {
            cout << thresholdOrDefault(v) << "\n";
        }
    } else {
        cin >> v;
        cout << thresholdOrDefault(v) << "\n";
    }
    return 0;
}

 

Solution Details

  • template<typename T = int> makes the function default to int if no type is specified.
  • def = {} uses value initialization → 0 for numbers, "" for strings, etc.
  • If v is negative, the function returns def, otherwise it returns v.
     

👉 In simple words:
 If the input value is invalid (negative), the function falls back to a default. If it’s fine, the function just returns it.

Significance for Embedded Developers

  • In firmware, configuration values may be read from non-volatile memory (NVM/EEPROM).
     
  • If the value is invalid, a default safe value should be used instead.
     
  • Templates with defaults allow this behavior for multiple types (int, float, etc.) without extra code.
     
Loading...

Input

5

Expected Output

5