2DPoint template
Define a templated struct named 2DPoint with the following member variables:
T xT y
It should include a default and parameterized constructor.
Answer
#include <iostream>
template <typename T>
struct 2DPoint {
T x;
T y;
// Default constructor
2DPoint() : x(0), y(0) {}
// Parameterized constructor
2DPoint(T xVal, T yVal) : x(xVal), y(yVal) {}
// Print coordinates
void print_coordinates() const {
std::cout << "x: " << x << ", y: " << y << std::endl;
}
};
// `main` serves as an example usecase
int main() {
// Create instances of 2DPoint with different numeric types
// Using int
2DPoint<int> point1(1, 2);
std::cout << "Point 1 (int):" << std::endl;
point1.print_coordinates();
std::cout << std::endl;
// Using float
2DPoint<float> point2(1.5f, 2.5f);
std::cout << "Point 2 (float):" << std::endl;
point2.print_coordinates();
std::cout << std::endl;
// Using double
2DPoint<double> point3(1.75, 2.75);
std::cout << "Point 3 (double):" << std::endl;
point3.print_coordinates();
return 0;
}