Skip to content

Instantly share code, notes, and snippets.

@csullivan
Last active February 20, 2017 15:28
Show Gist options
  • Save csullivan/6c08967bfd1006956d40a9a45aa41180 to your computer and use it in GitHub Desktop.
Save csullivan/6c08967bfd1006956d40a9a45aa41180 to your computer and use it in GitHub Desktop.
Example showing how something like duck typing can be resolved by the compiler using the curiously recursive template pattern in C++14
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment