in Programming
3,112 views
1 vote
1 vote
A function that  does the same operation on different data types is to be implemented using

a) macros   b) overloading  c) function templates  d) default arguments
in Programming
3.1k views

1 Answer

3 votes
3 votes
  • Function Template enables us to define a function that works for multiple data types.
template <typename T>
int compare(T a,T b) {
	if(a < b) return -1;
	else if(a > b) return 1;
	else return 0;
}

int main() {
	int x = 2;
	int y = 3;
	printf("%d\n",compare(x,y));

	double a = 2.3;
	double b = 1.3;
	printf("%d\n",compare(a,b));
}
by

4 Comments

return_type function_name( parameter list ) {
  // body
}
  • in the case of overloading only function_name remains same. Other things may change.
0
0

Thanks Debashish for your clarification.  However , I got a very beautiful  answer regarding the same which I want to share with you all  - 

 "The advantage of templates in a situation where you want to do the same set of operations on many different data types, is that the compiler will handle for you at compile time any possible new type you may create in the future that uses the templated function. if you were to use function overloading, you'd have to create a new function overload every time you created a new type that you wanted to pass to the specific function. "

1
1
why not macros??we can pass parameters to macros as well and sometimes they are more efficient then functions..
0
0
Answer:

Related questions