Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <vector>
- #include <set>
- class Base {
- };
- template <typename T>
- class Derived_CRTP : public Base {
- public:
- // a single getter which returns "by name" any object with the name 'data' regardless of its type.
- auto& get_data() { return static_cast<T*>(this)->data; }
- };
- class Derived1 : public Derived_CRTP<Derived1> {
- public:
- // here data is a vector of doubles
- std::vector<double> data = {1,2,3};
- };
- class Derived2 : public Derived_CRTP<Derived2> {
- public:
- // but here its a set of integers
- std::set<int> data = {1};
- };
- int main() {
- Derived1 d1;
- Derived2 d2;
- // in either case, the get_data function returns the underlying member by name, regardless of its type.
- auto a_vector = d1.get_data();
- auto a_set = d2.get_data();
- // pretty close to duck typing if you ask me!
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement