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.

  1. template <typename T>: Declares a template with a type parameter T.

  2. T absValue(T value): Defines a function template named absValue that takes a parameter of type T and returns its absolute value.

  3. return (value < 0) ? -value : value;: Uses the ternary operator to return the absolute value of the input parameter value. If value is less than 0, it returns -value; otherwise, it returns value.

  4. int main() {: Starts the main function.

  5. int intValue = -5; and double doubleValue = -7.5;: Declares and initializes two variables, one of type int and one of type double, both with negative values.

  6. int absInt = absValue(intValue); and double absDouble = absValue(doubleValue);: Calls the absValue function template to obtain the absolute values of intValue and doubleValue and stores the results in absInt and absDouble.

  7. std::cout << "Absolute value of " << intValue << " is: " << absInt << std::endl;: Prints the absolute value of intValue to the standard output.

  8. std::cout << "Absolute value of " << doubleValue << " is: " << absDouble << std::endl;: Prints the absolute value of doubleValue to the standard output.

  9. return 0;: Indicates successful program execution.