#include <iostream>
// Base class for entities
class entity
{
public:
virtual void do_walk() { std::cout << "I like walking" << std::endl; };
};
// A class property for healer characters
class healer
{
public:
// interface
virtual void do_heal() = 0;
};
// A class property for healer npcs
class merchant
{
public:
// interface
virtual void do_sell() = 0;
};
// implementation of the healer property
class healer_implementation : public healer
{
public:
virtual void do_heal() { std::cout << "I heal people" << std::endl; }
};
// implementation of the healer property
class merchant_implementation : public merchant
{
public:
virtual void do_sell() { std::cout << "I sell things" << std::endl; }
};
// To deduce the implementation of a property, we'll use the template property which will be specialized for each property and reference an implementation
template<typename T>
class property
{};
template<>
class property<merchant>
{
public: typedef merchant_implementation implementation;
};
template<>
class property<healer>
{
public: typedef healer_implementation implementation;
};
// This class is a class helper to deduce the right class type from a list of property for an entity
template<class... Property>
class factory
{
public:
class custom : public property<Property>::implementation..., public entity {};
};
int main()
{
entity* bob = new factory<healer, merchant>::custom();
// bob will try to sell things
merchant* m = dynamic_cast<merchant*>(bob);
if (m)
m->do_sell();
// bob will try to heal people
healer* h = dynamic_cast<healer*>(bob);
if (h)
h->do_heal();
// and as an entity, bob can walk
bob->do_walk();
entity* frank = new factory<healer>::custom();
// frank will try to sell things
m = dynamic_cast<merchant*>(frank);
if (m)
m->do_sell();
// frank will try to heal people
h = dynamic_cast<healer*>(frank);
if (h)
h->do_heal();
// and as an entity, frank can walk
frank->do_walk();
}