How to write generic abs function to get absolute value from different type numbers in C++

1 Answer

0 votes
#include <iostream>

using std::cout;
using std::endl;

template <class T> T abs(T n)
{
	return n < 0 ? -n : n;
}

int main()
{
	cout << abs(-4) << endl;

	cout << abs(-12343.56) << endl;

	cout << abs(-9999999L) << endl;

	cout << abs(-3.14F) << endl;

	return 0;
}


/*
run:

4
12343.6
9999999
3.14

*/

 



answered Aug 2, 2018 by avibootz
...