Reputation: 23
I was going through a textbook and found a question regarding templates.
Q. Rewrite this function using templates to work with any type. List the operations that any type using this template function must support
int FindLargest(const int& a, const int& b) {
int ret;
if (a > b) {
ret = a;
}
else {
ret = b;
}
return ret;
}
My answer:
template<typename T>
T FindLargest(const T& a, const T& b) {
T ret;
if (a > b) {
ret = a;
}
else {
ret = b;
}
return ret;
}
It was easy to answer first part(rewrite using template..) but I am confused with the second sentence of the question. what is it trying to say?
Upvotes: 2
Views: 111
Reputation: 106066
2) is asking you which things the type T
needs to be able to do for the template to compile and operate correctly...
Consider:
T ret;
For the above to work, T
must have a default constructor.
if (a > b) {
For the above to work, there must be some >
operator that can - directly or indirectly - compare two instances of the type, returning something that either is of boolean type, or can be converted thereto. The two most obvious examples of direct support would be either an bool T::operator>(const T& rhs) const
member function or a stand-alone bool operator>(const T& lhs, const T& rhs)
function. An example of indirect support is an T::operator
sometype() const
conversion operator to a type - such as double
- that itself can be compared with >
.
ret = a;
For the above to work, there needs to be a (copy / non-move) assignment operator.
Continue this style of analysis to fully answer the question.
Upvotes: 0
Reputation:
List the operations that any type using this template function must support
This part of the question is asking for what generic programming people call type constraint or concept.
Let's take a look at this line:
if (a > b) {
This line is comparing a
and b
using operator >
. That means type T
must support the >
comparison. Otherwise, the code does not compile.
As a quick experiment, you may try to declare an empty class and instantiate the function template with it.
class Empty {};
int main() {
Empty x, y;
FindLargest(x, y);
}
The compiler may emits an error message like:
error: no match for 'operator>' (operand types are 'const Empty' and 'const Empty')
So, one of several items in your list should be the larger-than comparison operation using >
. Also note that this function template also requires other operations. I will leave it to you to find out.
Upvotes: 2