Class Rectangle wants to be declared like this: Recangle<int>


Just confirming with you guys, please tell me if I am correct. The triangle brackets <> are used when a class has been defined with a template data type. This is so the same class can be used with different data types. (i.e. std::vectors that can hold anything!)

In the Graphics tutorial, sometimes a Rectangle<int> is called and sometimes a Rectangle<float> is used. Originally I thought it was odd that it was even used in the first place, but now, I understand that it exists in order to allow you to pass numbers as arguments as types int, float, double, long etc. Is that correct?

If that’s correct, can’t the Rectangle class not just have different constructors one that accepts int arguments, another for floats, etc. ?

The template type argument also determines how the values are stored internally (i.e., as ints, floats, doubles,…) and not just the constructor signature. Simply overloading the constructor wouldn’t allow you to do that.

Except if the class does type erasure.

…which would probably imply dynamic memory allocation.

Rectangle<T> lives entirely on the stack.

A bit less theoretical:

Rectangle<int> and Rectangle<float> are different types, as if you had defined them completely separate. That’s why no overloading is possible.

But there are a few convenience methods:
Rectangle<Type>::toFloat() converts a Rectangle of any type into a Rectangle<float>, and some more…

1 Like

Thanks all!