Color.hpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #ifndef CORE_COLOR_HPP
  2. #define CORE_COLOR_HPP
  3. namespace Core {
  4. using ColorChannel = unsigned char;
  5. template<int N>
  6. class Color final {
  7. static_assert(N >= 1 && N <= 4, "a color has 1 to 4 channels");
  8. ColorChannel data[static_cast<unsigned int>(N)] = {};
  9. public:
  10. Color() = default;
  11. template<typename OT, typename... Args>
  12. Color(OT a, Args&&... args) {
  13. init<0>(a, args...);
  14. }
  15. private:
  16. template<int I>
  17. void init() {
  18. static_assert(I == N,
  19. "color channel parameters do not match its size");
  20. }
  21. template<int I, typename OT, typename... Args>
  22. void init(OT a, Args&&... args) {
  23. data[I] = static_cast<ColorChannel>(a);
  24. init<I + 1>(args...);
  25. }
  26. public:
  27. float asFloat(int index) const {
  28. return data[index] * (1.0f / 255.0f);
  29. }
  30. ColorChannel& operator[](int index) {
  31. return data[index];
  32. }
  33. const ColorChannel& operator[](int index) const {
  34. return data[index];
  35. }
  36. };
  37. using Color4 = Color<4>;
  38. using Color3 = Color<3>;
  39. using Color2 = Color<2>;
  40. using Color1 = Color<1>;
  41. }
  42. #endif