Skip to content

Instantly share code, notes, and snippets.

@varphone
Created November 11, 2018 15:14
Show Gist options
  • Save varphone/569cb818c6e3a668b1243533f229bbd8 to your computer and use it in GitHub Desktop.
Save varphone/569cb818c6e3a668b1243533f229bbd8 to your computer and use it in GitHub Desktop.
math2d.hpp
#ifndef EXT_MATH2D_HPP
#define EXT_MATH2D_HPP
#include <cmath>
#include <iostream>
namespace ext
{
template <typename T>
struct Point
{
typedef T ValueType;
float x;
float y;
};
using PointF32 = Point<float>;
using PointF64 = Point<double>;
using PointF = PointF32;
template <typename T>
T center_of(T const &a, T const &b, T const &c)
{
typename T::ValueType cx = (a.x + b.x + c.x) / 3;
typename T::ValueType cy = (a.y + b.y + c.y) / 3;
return {cx, cy};
}
template <typename T>
typename T::ValueType distance_of(T const &a, T const &b)
{
typename T::ValueType dx = a.x - b.x;
typename T::ValueType dy = a.y - b.y;
return std::sqrt(dx * dx + dy * dy);
}
template <typename T>
std::ostream &operator<<(std::ostream &os, Point<T> const &value)
{
os << "PointF(" << value.x << "," << value.y << ")";
return os;
}
} // namespace ext
#ifdef _TEST_MAIN_
int main(int argc, char **argv)
{
ext::PointF p1{1, 1};
ext::PointF p2{2, 2};
ext::PointF p3{3, 3};
std::cout << "center_of = " << ext::center_of<ext::PointF>(p1, p2, p3)
<< std::endl;
std::cout << "distance_of = " << ext::distance_of<ext::PointF>(p1, p2)
<< std::endl;
std::cout << "distance_of = "
<< ext::distance_of<ext::PointF64>({3, 4}, {5, 6}) << std::endl;
return 0;
}
#endif
#endif // EXT_MATH2D_HPP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment