c++ abs template
#include <iostream>
template <typename T>
T absValue(T value) {
return (value < 0) ? -value : value;
}
int main() {
int intValue = -5;
double doubleValue = -7.5;
int absInt = absValue(intValue);
double absDouble = absValue(doubleValue);
std::cout << "Absolute value of " << intValue << " is: " << absInt << std::endl;
std::cout << "Absolute value of " << doubleValue << " is: " << absDouble << std::endl;
return 0;
}
Explanation:
1. #include <iostream>
: Includes the necessary header file for input and output operations.
template <typename T>
: Declares a template with a type parameterT
.T absValue(T value)
: Defines a function template namedabsValue
that takes a parameter of typeT
and returns its absolute value.return (value < 0) ? -value : value;
: Uses the ternary operator to return the absolute value of the input parametervalue
. Ifvalue
is less than 0, it returns-value
; otherwise, it returnsvalue
.int main() {
: Starts the main function.int intValue = -5;
anddouble doubleValue = -7.5;
: Declares and initializes two variables, one of typeint
and one of typedouble
, both with negative values.int absInt = absValue(intValue);
anddouble absDouble = absValue(doubleValue);
: Calls theabsValue
function template to obtain the absolute values ofintValue
anddoubleValue
and stores the results inabsInt
andabsDouble
.std::cout << "Absolute value of " << intValue << " is: " << absInt << std::endl;
: Prints the absolute value ofintValue
to the standard output.std::cout << "Absolute value of " << doubleValue << " is: " << absDouble << std::endl;
: Prints the absolute value ofdoubleValue
to the standard output.return 0;
: Indicates successful program execution.