Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <iostream>
struct Vector2 {
float x;
float y;
Vector2(float x = 0, float y = 0) {
this->x = x;
this->y = y;
}
};
template <typename T>
T min(T a, T b) {
return a < b ? a : b;
}
template <>
Vector2 min(Vector2 a, Vector2 b) {
return Vector2(min(a.x, b.x), min(a.y, b.y));
}
template <typename T>
T max(T a, T b) {
return a > b ? a : b;
}
template <>
Vector2 max(Vector2 a, Vector2 b) {
return Vector2(max(a.x, b.x), max(a.y, b.y));
}
template <typename T>
T clamp(T value, T lowerBound, T upperBound) {
return min(max(lowerBound, value), upperBound);
}
std::ostream &operator<<(std::ostream &os, const Vector2 &v) {
os << v.x << ", " << v.y;
return os;
}
int main() {
Vector2 lowerBound(-100, -100);
Vector2 upperBound(100, 100);
std::cout << clamp(Vector2(200, 200), lowerBound, upperBound) << std::endl;
std::cout << clamp(Vector2(-200, -200), lowerBound, upperBound) << std::endl;
std::cout << clamp(Vector2(-10, -134), lowerBound, upperBound) << std::endl;
std::cout << clamp(Vector2(10, 134), lowerBound, upperBound) << std::endl;
std::cout << min(Vector2(-10, -134), lowerBound) << std::endl;
std::cout << max(Vector2(10, 134), upperBound) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment