explicit_type.h 966 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #pragma once
  2. #include "typetraits.h"
  3. /**
  4. * Helper type that can be used as one of the parameters in function declaration
  5. * to limit the number of types this function can be called with.
  6. *
  7. * Example usage:
  8. * @code
  9. * void CharOnlyFunction(TExplicitType<char> value);
  10. * void AnythingFunction(char value);
  11. *
  12. * CharOnlyFunction('c'); // Works.
  13. * CharOnlyFunction(1); // Compilation error.
  14. * CharOnlyFunction(1ull); // Compilation error.
  15. *
  16. * AnythingFunction('c'); // Works.
  17. * AnythingFunction(1); // Works.
  18. * AnythingFunction(1ull); // Works.
  19. * @endcode
  20. */
  21. template <class T>
  22. class TExplicitType {
  23. public:
  24. template <class OtherT>
  25. TExplicitType(const OtherT& value, std::enable_if_t<std::is_same<OtherT, T>::value>* = nullptr) noexcept
  26. : Value_(value)
  27. {
  28. }
  29. const T& Value() const noexcept {
  30. return Value_;
  31. }
  32. operator const T&() const noexcept {
  33. return Value_;
  34. }
  35. private:
  36. const T& Value_;
  37. };