trait.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #ifndef AAB
  2. #define AAB
  3. #include <functional>
  4. #include <iostream>
  5. #include <memory>
  6. using namespace std;
  7. struct Trait
  8. {
  9. public:
  10. Trait(const Trait &trait) = default;
  11. Trait(Trait &&trait) = default;
  12. Trait &operator=(const Trait &trait) = default;
  13. Trait &operator=(Trait &&trait) = default;
  14. virtual ~Trait() = default;
  15. template <typename T>
  16. explicit Trait(T t)
  17. : container(std::make_shared<Model<T>>(std::move(t)))
  18. {
  19. }
  20. template <typename T>
  21. T cast()
  22. {
  23. auto typed_container = std::static_pointer_cast<const Model<T>>(container);
  24. return typed_container->m_data;
  25. }
  26. private:
  27. struct Concept
  28. {
  29. // All need to be explicitly defined just to make the destructor virtual
  30. Concept() = default;
  31. Concept(const Concept &concept) = default;
  32. Concept(Concept &&concept) = default;
  33. Concept &operator=(const Concept &concept) = default;
  34. Concept &operator=(Concept &&concept) = default;
  35. virtual ~Concept() = default;
  36. };
  37. template <typename T>
  38. struct Model : public Concept
  39. {
  40. Model(T x)
  41. : m_data(move(x))
  42. {
  43. }
  44. T m_data;
  45. };
  46. std::shared_ptr<const Concept> container;
  47. };
  48. #endif