In embedded firmware, variables must often be restricted to safe operating ranges (e.g., limiting a PWM duty cycle to 0-255 or a servo angle to -45 to +45). Legacy code frequently uses unsafe preprocessor macros (e.g., #define CLAMP), which suffer from type-safety issues and double-evaluation bugs.
Your task is to implement a function template named clamp_value. It must accept three parameters of a generic type T: value, min_limit, and max_limit. It returns the value constrained within the range [min_limit, max_limit].
value is less than min_limit, return min_limit.value is greater than max_limit, return max_limit.value.The function must work correctly for both integers and floating-point types.
Program Flow:
N (number of test cases).N times:type_code ('i' for int, 'f' for float).type_code is 'i':val, min, max.clamp_value<int> with these arguments.type_code is 'f':val, min, max.clamp_value<float> with these arguments.10.0).Input Format:
N (number of test cases).N lines: Character type_code, followed by three numbers (val, min, max).Output Format:
Result: <value>10.0, -5.0).Example:
Example 1 (Mixed Types)
Input:
4
i 100 0 255
i 300 0 255
f 12.5 0.0 10.0
f -5.0 -10.0 0.0Output:
Result: 100
Result: 255
Result: 10.0
Result: -5.0Constraints:
N range: 1 to 20val, min, max will be valid numeric types.min_limit <= max_limit is always true.template <typename T> syntax.
Input
4 i 100 0 255 i 300 0 255 f 12.5 0.0 10.0 f -5.0 -10.0 0.0
Expected Output
Result: 100 Result: 255 Result: 10.0 Result: -5.0