Skip to content

Instantly share code, notes, and snippets.

@chiiph
Last active Dec 16, 2015
Embed
What would you like to do?
class Base
{
public:
Base() {}
virtual ~Base() {}
};
class NotCopyable
{
public:
NotCopyable() {}
NotCopyable(const NotCopyable &) = delete;
NotCopyable &operator=(const NotCopyable &) = delete;
};
class FirstComponent : public NotCopyable
{
public:
FirstComponent(float value) : _value(value) {}
virtual ~FirstComponent() {}
float _value;
};
class SecondComponent : public NotCopyable
{
public:
SecondComponent(const std::string &value) : _value(value) {}
virtual ~SecondComponent() {}
std::string _value;
};
class GameObject : public Base, public FirstComponent, public SecondComponent
{
public:
GameObject() : Base(), FirstComponent(42.0f), SecondComponent(R"(I'm a GameObject!)") {}
virtual ~GameObject() {}
};
class GameObject2 : public Base, public SecondComponent
{
public:
GameObject2() : Base(), SecondComponent(R"(And I'm a GameObject2)") {}
virtual ~GameObject2() {}
};
int main()
{
std::vector<std::shared_ptr> objects;
objects.push_back(std::make_shared<GameObject>());
objects.push_back(std::make_shared<GameObject2>());
int order = 0;
std::for_each(objects.begin(), objects.end(), [&] (std::shared_ptr object) {
if(auto firstComponent = std::dynamic_pointer_cast(object))
{
std::cout << "The object at " << order << " implements FirstComponent" << std::endl;
std::cout << _value << std::endl;
}
if(auto secondComponent = std::dynamic_pointer_cast(object))
{
std::cout << "The object at " << order << " implements SecondComponent" << std::endl;
std::cout << _value << std::endl;
}
order++;
});
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment