Generic Programming in c++

Hello.

In the following code

template <typename T>
T max(T &a, T &b)
{
if(a>b)
return a;
else
return b;
}

Is it necessary that the arguments of the function are 'call by reference'?
Only if you want to return a reference (Tip: you're not returning a reference).
Is it necessary that the arguments of the function are 'call by reference'?
no, it is not
I would actually use call by const reference here because a and b aren't modified.

You could just use call by value but that would be slower for most objects (objects with a size greater than the size of a pointer)
It's not necessary but it's usually a good idea to pass arguments of template types by reference because some types are costly to copy and pass by reference avoids copies being made. For simple types like int and double it doesn't really matter.

As Gamer2015 said, you should use const references here, otherwise you will not be able to pass in literals to your function.
1
2
3
4
// Your function would fail here because 
// literals (and other temporary objects)
// can't bind to non-const references.
std::cout << max(5, 6) << std::endl;
Last edited on
Topic archived. No new replies allowed.