Skip to content

Instantly share code, notes, and snippets.

@flisboac
Created August 16, 2019 05:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flisboac/d930f69ded0892eabbe2ee782c5ffc9f to your computer and use it in GitHub Desktop.
Save flisboac/d930f69ded0892eabbe2ee782c5ffc9f to your computer and use it in GitHub Desktop.
Example of usage of CRTP for compile-time polymorphism. https://glot.io/snippets/ff2rlis81s
#include <iostream>
#include <string>
using namespace std;
// Utility class, mostly.
// The secret sauce is static_cast.
// as_subclass() is there only to help deduce when to const things.
template <typename TSubclass>
class crtp_template {
protected:
using subclass_type = TSubclass;
subclass_type& as_subclass() { return static_cast<subclass_type&>(*this); }
subclass_type const& as_subclass() const { return static_cast<subclass_type const&>(*this); }
};
// Here we have a base class. A compile-time template.
// It may depend on some subclass methods to do its job.
template <typename TSubclass>
class entity_template : public crtp_template<TSubclass> {
public:
void greet() { std::cout << this->as_subclass().make_greet() << std::endl; }
};
class entity : public entity_template<entity> {
private:
entity(std::string name) : name_(name) {}
std::string make_greet() {
using namespace std::literals;
return "Hello, "s + this->name_ + "!";
}
private:
std::string name_ = "there";
};
int main() {
using namespace std::literals;
entity world("world"s);
world.greet();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment