Hello all,
I'm trying to get a grasp of the difference between specializing a function
template and overloading it. The example below has a primary template, a
specialization and an overload. Note that the overload is identical to the
specialization except, of course, for the missing "template <>".
I don't know if my questions will be a bit too broad or not, but I thought
I'd give it shot... When is overloading preferable to specialization? When
is specialization preferable to overloading? What is the intended
conceptual difference between the two? Any other guidance on other things I
need to know but don't know enough yet to even ask?
Thanks everyone - this group has been an invaluable resource to me and I
sure appreciate the time of those who have so generously assisted me!
Thanks,
Dave
#include <iostream>
using namespace std;
struct foo
{
int data;
bool operator<(const foo &rhs) const
{
return data < rhs.data;
}
};
template <typename T>
const T &my_max(cons t T &a, const T &b)
{
cout << "Point 1" << endl;
return (a < b) ? b : a;
}
template <>
const foo &my_max(cons t foo &a, const foo &b)
{
cout << "Point 2" << endl;
return (a < b) ? b : a;
}
const foo &my_max(cons t foo &a, const foo &b)
{
cout << "Point 3" << endl;
return (a < b) ? b : a;
}
int main()
{
foo a = {5};
foo b = {10};
// Yields "Point 3" as non-templates are
// preferred.
cout << my_max(a, b).data << endl;
return 0;
}
Comment