Advertisement
Guest User

Untitled

a guest
Feb 20th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <set>
  5.  
  6. class Base {
  7. };
  8.  
  9. template <typename T>
  10. class Derived_CRTP : public Base {
  11. public:
  12.  
  13. // a single getter which returns "by name" any object with the name 'data' regardless of its type.
  14. auto& get_data() { return static_cast<T*>(this)->data; }
  15.  
  16. };
  17.  
  18. class Derived1 : public Derived_CRTP<Derived1> {
  19. public:
  20. // here data is a vector of doubles
  21. std::vector<double> data = {1,2,3};
  22. };
  23.  
  24.  
  25. class Derived2 : public Derived_CRTP<Derived2> {
  26. public:
  27. // but here its a set of integers
  28. std::set<int> data = {1};
  29. };
  30.  
  31.  
  32.  
  33. int main() {
  34.  
  35. Derived1 d1;
  36. Derived2 d2;
  37.  
  38. // in either case, the get_data function returns the underlying member by name, regardless of its type.
  39. auto a_vector = d1.get_data();
  40. auto a_set = d2.get_data();
  41.  
  42. // pretty close to duck typing if you ask me!
  43.  
  44. return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement