Mapping two object types in C++ - c++

I'm creating a small simulation framework in C++. I want to separate the pure simulation-related stuff from the displaying. So I have classes like:
class Pointer : public SimulationObject {};
class Particle : public SimulationObject {};
class LearningObserver : public SimulationObject {};
which all are derived from SimulationObject, but only some(!) have a visual representation:
class Renderable {
public:
virtual void render() const = 0;
//may also include reference to assosciated SimulationObject
}
class PointerRenderable : public Renderable {
void render() const { std::cout << "Render a pointer" << std::endl;
};
class ParticleRenderable : public Renderable {
void render() const { std::cout << "Render a particle" << std::endl;
};
Now whenever a new SimulationObject is added to my Simulation (at runtime) I want to check, if there is a class that renders it. If so, I want to create an instance of it. My first idea was to use polymorphy:
class AbstractRenderFactory {
virtual Renderable * provideRenderable(SimulationObject * so) const = 0;
};
class ConcreteRenderFactory {
void PointerRenderable * provideRenderable(Pointer * pointer) {
return new PointerRenderable();
}
// further provideRenderable's
};
However using derived types when overridding methods obviously doesn't work (the base-method gets called). Also this is problematic since the function would only be partially defined.
Another idea was to provide an actual mapping of types:
std::map<std::type_index, std::type_index> renderTable;
but I can't get instances by just using the type_info. Do you have an idea?
Update: I tried using the visitor pattern, however I ran into similar problems. My visitor classes look like this:
class RenderVisitor {
public:
virtual Renderable * visit(SimulationObject * so) {
// I would like to have this method abstract, but I could live with this
return 0;
}
};
class MyRenderVisitor : public RenderVisitor {
public:
Renderable * visit(Pointer * pointer) const {
return new PointerRenderable();
}
};
Plus the new base class for my Simulation parts.
class SimulationObject {
public:
Renderable * accept(RenderVisitor * renderer) {
return renderer->visit(this);
}
};
The visit-method of MyRenderVisitor obviously isn't recognized as an override of the base-class, but I was hoping that with the this pointing to the actual (derived) type, the right method (that of MyRenderVisitor) would be called.
My test-scenario looks like this:
RenderVisitor * rv = new MyRenderVisitor();
SimulationObject * pointer = new Pointer();
Renderable * renderable = pointer->accept(rv);
renderable->render();
// renderable = 0 -> seg-fault
Or is just my implementation wrong?

Yes, it seems you need double-dispatch technique, it can be implemented by applying the Visitor pattern.
The code to illustrate the idea:
Interface part:
class SimulationObject {
public:
virtual void Accept(RenderableVisitor* visitor) const = 0;
...
};
class RenderableVisitor {
public:
virtual void Visit(Pointer* pointer) const = 0;
virtual void Visit(Particle* particle) const = 0;
virtual void Visit(LearningObserver* learning_observer) const = 0;
}
Concrete part:
class Pointer : public SimulationObject {
public:
virtual void Accept(RenderableVisitor* visitor) const
{
visitor->Visit(this);
}
};
class Particle : public SimulationObject {
public:
virtual void Accept(RenderableVisitor* visitor) const
{
visitor->Visit(this);
}
};
class LearningObserver : public SimulationObject {
public:
virtual void Accept(RenderableVisitor* visitor) const
{
visitor->Visit(this);
}
};
class ConcreteRenderableVisitor : public RenderableVisitor {
public:
virtual void Visit(Pointer* pointer) const
{
std::cout << "Render a pointer" << std::endl;
}
virtual void Visit(Particle* particle) const
{
std::cout << "Render a particle" << std::endl;
}
virtual void Visit(LearningObserver* learning_observer) const
{
std::cout << "Render a learning observer" << std::endl;
}
}
The ConcreteRenderableVisitor class implements logic for each leaf of SimulationObject class hierarchy.
Client code:
ConcreteRenderableVisitor visitor;
Particle particle;
particle.Accept(&visitor); // Render a particle by the visitor.
Client code 2 (more abstract example to proof the technique):
RenderableVisitor* visitor = new ConcreteRenderableVisitor;
SimulationObject* object = new Particle;
object->Accept(visitor);

Related

Architecture of sub-classes in C++

I learn C++ OOP-paradigm and want to ask related question:
Assumption
We have a base class:
class Base {
public:
virtual SomeType PowerMethod() { return SomeType{} };
}
We have a variable target and subclass which realizes some calculations with target variable based on the constructor's parameter (simple calculations or complicated calcs):
class Calc : public Base {
public: // using only public access to simplify real code structure
SomeType target;
void Simple() { target = 1; };
void Complex(){ target = 10000; };
explicit Calc(bool isSimple) {
if(isSimple)
Simple();
else
Complex();
}
};
Question
How to optimally realize two classes which based on different methods (Simple or Complex) but provide the same functionality of PowerMethod()?
My solution
class SimpleCalc : public Calc {
bool isSimple = true;
public:
SomeType PowerMethod() override {
Calc CalcInstance(isSimple);
return CalcInstance.target;
};
};
class ComplexCalc : public Calc {
bool isSimple = false;
public:
SomeType PowerMethod() override {
Calc CalcInstance(isSimple);
return CalcInstance.target;
};
};
This solution is pretty "ugly" and I want to ask you how to make it more readable.
Thank you!
I think that in your code, you didn't mean to craete a new Calc object, but instead call it on the superclass. This can be done like so:
Calc::Simple();
You can override the method PowerMethod, but still call the superclass's code:
virtual SomeType PowerMethod() override {
//do something
Base::PowerMethod();
}
If your problem is more complicated, and polymorphism and superclasses can't help you, you can always declare some method protected, so that only subclasses can access it. So, you could for example do this:
class Calc : public Base {
protected:
SomeType target;
void Simple() { target = 1; };
void Complex(){ target = 10000; };
public:
explicit Calc(bool isSimple) {
if(isSimple)
Simple();
else
Complex();
}
};
class SimpleCalc : public Calc {
public:
SomeType PowerMethod() override {
Calc::Simple();
return Calc::target;
};
};
class ComplexCalc : public Calc {
public:
SomeType PowerMethod() override {
Calc::Complex();
return Calc::target;
};
};
If your target is to learn OOP then you can use a factory design pattern to create your final calculator based on isSimple condition:
#include <iostream>
class Base
{
public:
Base()
{
target = 0;
}
int target;
virtual void PowerMethod() = 0;
};
class SimpleCalc : public Base
{
virtual void PowerMethod() { target = 0; }
};
class ComplexCalc : public Base
{
virtual void PowerMethod() { target = 1000; }
};
class CalcFactory
{
public:
virtual Base* createCalc(bool isSimple)
{
if (isSimple)
return new SimpleCalc();
else
return new ComplexCalc();
}
};
int main()
{
CalcFactory factory;
Base * base1 = factory.createCalc(true);
Base * base2 = factory.createCalc(false);
base1->PowerMethod();
base2->PowerMethod();
std::cout << base1->target << std::endl;
std::cout << base2->target << std::endl;
}

How to handle abstraction and specialization of a class and its attributes?

Apologies for this quite abstract title.
More clearly:
I have two classes Controler and Interface (hardware sense, unrelated to design pattern)
Both are abstract with some pure virtual methods and hence intended to be subclassed
I need each Controler created to be associated with an Interface object
Each Controler subclass only work with a subset of Interface subclasses (ControlerA + InterfaceA or ControlerB + InterfaceB but not ControlerA + InterfaceB)
Each Interface subclass has its own methods not inherited (this is why only one kind of Controler can use it)
The Controler base class need to call some method of the base class Interface
I try to pass an Interface objet to the Controler constructor, hence in my class definition the Interface attribute represents the abstract base class. But if my Controler subclass A need to call a specific method of the Interface A, an compilation error is raised as the Interface base class doesn't own this method.
The only workaround I found was to call dynamic_cast, but it obviously seems wrong.
Here are my Interface classes:
class Interface {
public:
Interface() {};
virtual void method() = 0;
};
class InterfaceA : public Interface {
public:
InterfaceA() : Interface() {};
void method() override { cout << "A overriding" << endl; }
void onlyA() { cout << "A only" << endl; }
};
class InterfaceB : public Interface {
public:
InterfaceB() : Interface() {};
void method() override { cout << "B overriding" << endl; }
void onlyB() { cout << "B only" << endl; }
};
Here are my Controler classes:
class Controler {
public:
Controler(Interface* i) : m_interface(i) {};
virtual void uniqueMethod() = 0;
void commonMethod() { m_interface->method(); }
Interface* m_interface;
};
class ControlerA : public Controler {
public:
ControlerA(InterfaceA* i) : Controler(i) {};
void uniqueMethod() override {dynamic_cast<InterfaceA *>(m_interface)->onlyA();}
};
class ControlerB : public Controler {
public:
ControlerB(InterfaceB* i) : Controler(i) {};
void uniqueMethod() override {dynamic_cast<InterfaceB *>(m_interface)->onlyB();}
};
And here is how I plan to use them:
auto ia = new InterfaceA();
auto ca = ControlerA(ia);
ca.commonMethod(); // Method defined in the base class
ca.uniqueMethod(); // Method defined in InterfaceA only
You can try it on Repl.it.
Is there any design pattern to solve this issue?
There is a problem indeed. There exists an invariant between the dynamic type of m_interface and the dynamic type of the object that implement Controler. But this invariant cannot be maintained by the Controler class. So the m_interface member is not a the right place.
The consequence is that you need to check at runtime that this member has the right type by using the dynamic_cast each time you call uniqueMethod. If the invariant is broken, the code will have UB because it would dereference a null pointer.
So this is not really a design pattern issue, but more fundamentally an object oriented programming recommendation: classes must ensure invariants.
class Controler {
public:
virtual void uniqueMethod() = 0;
virtual void commonMethod() = 0;
};
class ControlerA : public Controler {
public:
ControlerA(InterfaceA* i):m_interface{i} {
assert(dynamic_cast<InterfaceA*>(i)!=nullptr);
};
void uniqueMethod() override { m_interface->onlyA();}
void commonMethod() override { m_interface->method(); }
private: InterfaceA* m_interface;
};
class ControlerB : public Controler {
public:
ControlerB(InterfaceB* i):m_interface{i} {
assert(dynamic_cast<InterfaceB*>(i)!=nullptr);
};
void uniqueMethod() override { m_interface->onlyB();}
void commonMethod() override { m_interface->method(); }
private: InterfaceB* m_interface;
};
So now, it looks that we have a regular pattern, so this is where we can think about a more generic design:
template<class Inter,void(Inter::* OnlyFunc)()>
class ControlerImpl : public Controler {
public:
ControlerImpl(Inter* i):m_interface{i} {
assert(dynamic_cast<Inter*>(i)!=nullptr);
};
void uniqueMethod() override { (m_interface->*OnlyFunc)();}
void commonMethod() override { m_interface->method(); }
private: Inter* m_interface;
};
using ControlerA = ControlerImpl<InterfaceA,&InterfaceA::onlyA>;
using ControlerB = ControlerImpl<InterfaceB,&InterfaceB::onlyB>;

Exposing only the functions overriden by the derived object

I want to expose only the functions from the Abstract Class that have been overridden (implemented) by the derived Class.
For example: I have an Abstract Class called Sensor that is implemented by various different types of sensors. Some have more capabilities than others, so I don't want all functions to be exposed. Only the ones implemented. In the following example all sensors can produce DataA, but DataB and DataC are sensor specific. Some can produce all three, some 2 and some only DataA.
//Code Example
class Sensor{
public:
virtual DataContainer* getDataA() = 0; //pure virtual
virtual DataContainer* getDataB() {return null_ptr;}; //but this would appear in the derived objects
virtual DataContainer* getDataC() {return null_ptr;};
}
class SensorA : public Sensor {
public:
virtual DataContainer* getDataA(){
//code
}
}
class SensorAB : public Sensor {
public:
virtual DataContainer* getDataA(){
//code
}
virtual DataContainer* getDataB(){
//code
}
}
//main
Sensor* ab = new SensorAB();
ab->getDataB(); //GOOD
ab->getDataC(); // Not possible
Is there any way to achieve this?
You need more deep class hierarchy.
class Sensor...
class SensorA: virtual public Sensor...
class SensorB: virtual public Sensor...
class SensorAB: public SensorA, public SensorB...
Do not forget about virtual keyword.
Example:
class Sensor {
public:
virtual ~Sensor() {}
template<typename T>
bool CanConvert()
{
return dynamic_cast<T*>(this) != nullptr;
}
template<typename T>
T& Convert()
{
return dynamic_cast<T>(*this);
}
};
class SensorA: virtual public Sensor {
public:
virtual void DataA() = 0;
};
class SensorB: virtual public Sensor {
public:
virtual void DataB() = 0;
};
class SensorC: virtual public Sensor {
public:
virtual void DataC() = 0;
};
class SensorAB: public SensorA, public SensorB {
public:
void DataA() override {
std::cout << "SensorAB::DataA()" << std::endl;
}
void DataB() override {
std::cout << "SensorAB::DataB()" << std::endl;
}
};
Than you can use it:
void Func(Sensor& s)
{
if (s.CanConvert<SensorA>()) {
auto &s_a = s.Convert<SensorA>();
s_a.DataA();
}
if (s.CanConvert<SensorB>()) {
auto &s_b = s.Convert<SensorB>();
s_b.DataB();
}
if (s.CanConvert<SensorC>()) {
auto &s_c = s.Convert<SensorC>();
s_c.DataC();
}
}
...
SensorAB s_ab;
Func(s_ab);
Or you can use static polymorphysm. Create base class for every data type: SensorA, SensorB, SensorC. Than compose sensor with desired interface (SensorAB for example):
template <class Derived>
class SensorA
{
public:
void DataA() { static_cast<Derived*>(this)->DataAImpl(); }
};
template <class Derived>
class SensorB
{
public:
void DataB() { static_cast<Derived*>(this)->DataBImpl(); }
};
template <class Derived>
class SensorC
{
public:
void DataC() { static_cast<Derived*>(this)->DataCImpl(); }
};
class SensorAB: public SensorA<SensorAB>, public SensorB<SensorAB>
{
public:
void DataAImpl()
{
std::cout << "SensorAB::DataAImpl()" << std::endl;
}
void DataBImpl()
{
std::cout << "SensorAB::DataBImpl()" << std::endl;
}
};
Than you can use it:
SensorAB s_ab;
s_ab.DataA();
s_ab.DataB();
And you can use power of compilation time type check. But in this case you can cast only to SensorAB if you have base Sensor class, not in SensorA or SensorB.

How To Have A Single Interface Return Different Data Types?

In a nutshell, I want to use a single interface, IProducer, to create an object, IProduct. IProduct will have different components depending on which interface created it. The IProduct class will then be used by the IConsumer interface. The correct IConsumer class should be used (I do not want to do type checking myself) based on the derived type of IProduct.
I would essentially like to use the Strategy pattern (different behaviors behind a single interface), but with the added ability to return an object specific to the derived interface used. I want to abide by the Open/Close principle and not alter any of these existing classes when more functionality is added.
I would like to accomplish something like this (I'm sure the syntax is wrong somewhere but bear with me):
class IProduct {
public:
int intData;
};
class ProductA : public IProduct {
public:
float floatData;
};
class ProductB : public IProduct {
public:
bool boolData;
};
class IProducer {
public:
virtual IProduct* produce(void) = 0;
};
class ProducerA : public IProducer {
public:
IProduct* produce(void) {
return new ProductA;
}
};
class ProducerB : public IProducer {
public:
IProduct* produce(void) {
return new ProductB;
}
};
class IConsumer {
public:
virtual void consume(IProduct* prod) = 0;
};
class ConsumerA : public IConsumer {
public:
void consume(IProduct* prod) {
//I want to access the float!
}
};
class ConsumerB : public IConsumer {
public:
void consume(IProduct* prod) {
//I want to access the bool!
}
};
void main() {
IProducer* producer = ProducerFactory::create("ProducerA");
IProduct* product = producer->produce();
IConsumer* consumer = ConsumerFactory::create("ConsumerA");
consumer->consume(product); //I would like the correct consumer to be used here to deal with the ProductA class
}
If you think there is a better way to go about this I'm all ears. Thanks for your help!
What you need is a registry which maps IProduct implementations to the right IConsumer implementations. Basically its just an abstraction of a map:
class ConsumerRegistry
{
std::map<size_t, std::shared_ptr<IConsumer>> m_consumers;
public:
// we are not responsible for products, so lets allow plain ptrs here for more flexibility and less overhead
std::shared_ptr<IConsumer> GetConsumer(IProduct* product)
{
auto it = m_consumers.find(typeid(product).hash_code());
if (it == m_consumers.end())
return nullptr;
else
return it->second;
}
template<typename P>
void RegisterConsumer(std::shared_ptr<IConsumer> consumer)
{
m_consumers.emplace(typeid(P).hash_code(), consumer);
}
template<typename P>
void UnregisterConsumer()
{
m_consumers.erase(typeid(P).hash_code());
}
};
Either expose this class globally (e.g as singleton) or use it in the contexts where you need it. You register consumers like this:
reg.RegisterConsumer<ProductA>(new ConsumerA());
reg.RegisterConsumer<ProductB>(new ConsumerB());
We could also have a virtual void Register(ConsumerRegistry& reg) = 0; method inside IConsumer allowing for safer registering:
void ConsumerA::Register(ConsumerRegistry& reg, std::shared_ptr<IConsumer> self)
{
IConsumer::Register<ProductA>(reg, self);
}
// Required for friendship, can be static:
template<typename T>
void IConsumer::Register(ConsumerRegistry& reg, std::shared_ptr<IConsumer> self)
{
reg->RegisterConsumer<T>(self);
}
void ConsumberRegistry::RegisterConsumer(std::shared_ptr<IConsumer> consumer)
{
consumer->Register(*this, consumer);
}
Make both Register() and the low-level RegisterConsumer() methods private and let ConsumerRegistry and IConsumer be friends. Can be used like this then:
reg.RegisterConsumer(new ConsumerA());
reg.RegisterConsumer(new ConsumerB());
This is a solution I'm thinking of using. I'd appreciate any feedback.
I'm going to use the Visitor pattern and introduce the ProductVisitor class like so:
class IProductVisitor {
public:
explicit IProductVisitor() {}
virtual ~IProductVisitor(){}
virtual void visitA(ProductA* model) = 0;
virtual void visitB(ProductB* model) = 0;
};
class ProductTypeVisitor : public IProductVisitor {
public:
typedef enum {Unknown, A, B} ProductType;
explicit ProductTypeVisitor() : modelType(Unknown) {}
virtual ~ProductTypeVisitor(){}
virtual void visitA(ProductA* product) {
modelType = A;
}
virtual void visitB(ProductB* product) {
modelType = B;
}
ProductType getProductType(void) {
return modelType;
}
ProductType modelType;
};
class IProduct {
public:
IProduct() : intData(3) {}
virtual ~IProduct(){}
int intData;
virtual void accept(IProductVisitor* v) = 0;
};
class ProductA : public IProduct {
public:
ProductA() : IProduct(), floatData(5.5) { }
virtual ~ProductA(){}
float floatData;
void accept(IProductVisitor* v) {
v->visitA(this);
}
};
class ProductB : public IProduct {
public:
ProductB() : IProduct(),boolData(false) { }
virtual ~ProductB(){}
bool boolData;
void accept(IProductVisitor* v) {
v->visitB(this);
}
};
When making my factory, ConsumerFactor, I will use the ProductTypeVisitor class to determine what class the product is, dynamically cast it correctly (based off of the state of the enum), and then return a consumer initialized with the correct product.
class ConsumerFactory {
public:
explicit ConsumerFactory(void) {}
IConsumer* createFromProduct(IProduct* product) {
ProductTypeVisitor visitor;
product->accept(&visitor);
ProductTypeVisitor::ProductType productType = visitor.getProductType();
IConsumer* consumerPtr;
switch (productType) {
case ProductTypeVisitor::A :
consumerPtr = new ConsumerA(dynamic_cast<ProductA*>(product));
break;
case ProductTypeVisitor::B :
consumerPtr = new ConsumerB(dynamic_cast<ProductB*>(product));
break;
default:
std::cout << "Product type undefined. (throw exception)" << std::endl;
break;
}
return consumerPtr;
}
private:
ProductTypeVisitor visitor;
};
Finally, the code will look like this:
IProducer* producer = new ProducerA;
IProduct* product = producer->produce();
ConsumerFactory factory;
IConsumer* consumer = factory.createFromProduct(product);
consumer->consume();
Where the only thing that was ever specified, was ProducerA. Which, in my case, is the only thing that should be specified by the user. Also, I've isolated change areas to just two classes, the ConsumerFactory, and the IProductVisitor (which are very small changes to begin with).
If anyone could offer improvements or suggestions I'm all ears!
This is not the full solution (and maybe just a curiosity) but you can always do the tracking of types at compile time and use a bridging templated call to dispatch a product to the correct consumer.
#include <iostream>
template <class T>
class IProduct {
public:
virtual ~IProduct() {}
int intData;
typedef T consumer;
};
class ConsumerA;
class ProductA : public IProduct<ConsumerA> {
public:
float floatData;
};
class ConsumerB;
class ProductB : public IProduct<ConsumerB> {
public:
bool boolData;
};
template <class P, class C>
void apply(P* product, C* consumer) {
dynamic_cast<typename P::consumer*>(consumer)->consume(product);
}
template <class T>
class IConsumer {
public:
virtual void consume(IProduct<T>* prod) = 0;
};
class ConsumerA : public IConsumer<ConsumerA> {
public:
void consume(IProduct<ConsumerA>* prod) {
//I want to access the float!
std::cout << "ConsumerA" << std::endl;
std::cout << dynamic_cast<ProductA*>(prod)->floatData << std::endl;
}
};
class ConsumerB : public IConsumer<ConsumerB> {
public:
void consume(IProduct<ConsumerB>* prod) {
//I want to access the bool!
std::cout << "ConsumerB" << std::endl;
std::cout << dynamic_cast<ProductB*>(prod)->boolData << std::endl;
}
};
int main(int argc, char* argv[]) {
auto p_a = new ProductA;
auto c_a = new ConsumerA;
apply(p_a, c_a);
auto p_b = new ProductB;
auto c_b = new ConsumerB;
apply(p_b, c_b);
return 0;
}
I found this question while trying to solve a analogous issue. I ended up using std::any (which c++17 added to the language) to solve my problem. A single interface can return a std::any which you can cast back into the underlying type (via std::any_cast). In broad terms, std::any is like “hiding” types behind a void* pointer, but done in a type safe way, with full language and compiler support.
See:
std::any: How, when, and why
When should I use std::any
Related topic std::variant.

Right design pattern to deal with polymorphic collections of objects

Suppose I have the following classes:
class BaseObject {
public:
virtual int getSomeCommonProperty();
};
class Object1: public BaseObject {
public:
virtual int getSomeCommonProperty(); // optional
int getSomeSpecificProperty();
};
class BaseCollection {
public:
virtual void someCommonTask();
};
class Collection1: public BaseCollection {
public:
virtual void someCommonTask(); // optional
void someSpecificTask();
};
Each collection, derived from BaseCollection, deals with a specific object type (and only one type). But BaseCollection should be able to perform some tasks that are common to all objects, using only common object properties in BaseObject.
Currently, I have potentially three solutions in mind:
1) Store the objects list in BaseCollection, such as:
class BaseCollection {
vector<BaseObject*> objects;
};
The problem with this solution is that when I need to perform object-specific task in Collection1, I need a dynamic_cast<>, because I don't want to use virtual inherance for specific properties, applying to only one type of object. Considering that dynamic_cast<> could potentially get called millions of time per second, this seems an issue for a performance critical application.
2) Store the objects list in Collection1, such as:
class Collection1: public BaseCollection {
vector<Object1*> objects;
}
But then I need some way to access this object list in BaseCollection, to be able to perform some common tasks on them, ideally through an iterator. I would need to create a function that return a vector for the BaseCollection, but again, this does not seem very efficient, because the only way to do that is to create a new vector (potentially containing thousands of objects)...
3) Store the objects list in BaseCollection AND Collection1:
class BaseCollection {
public:
void someCommonTask(); // Use baseObjects
virtual void addObject() = 0;
protected:
vector<BaseObject*> baseObjects;
};
class Collection1: public BaseCollection {
vector<Object1*> objects;
public:
virtual void addObject() {
Object1* obj = new Object1;
objects.push_back(obj);
baseObjects.push_back(obj);
}
void someSpecificTask(); // Use objects, no need of dynamic_cast<>
}
Where the two lists actually contain the same objects. Is that as ugly as it sounds like?
I am looking for the right/correct/best design pattern for this type of problem and none of the 3 solutions exposed above really satisfies me...
Maybe it is possible to solve that problem with templates, but then I don't see a way to store a list of polymorphic collections like this:
vector<BaseCollection*> collections;
You can store all your objects of base and derived classes in one collection through the base class (smart) pointer. Using visitor design pattern and double dispatch mechanism you can call a function only on objects of a specific type without having to expose that function in the base class interface. For example:
#include <boost/intrusive_ptr.hpp>
#include <boost/bind.hpp>
#include <vector>
#include <algorithm>
#include <stdio.h>
struct Visitor { // Visitor design patter
virtual void visit(struct BaseObject&) {}
virtual void visit(struct Object1&) {}
};
struct BaseObject {
unsigned ref_count_; // intrusive_ptr support
BaseObject() : ref_count_() {}
virtual ~BaseObject() {}
virtual void accept(Visitor& v) { v.visit(*this); } // Visitor's double dispatch
virtual void getSomeCommonProperty() { printf("%s\n", __PRETTY_FUNCTION__); }
};
void intrusive_ptr_add_ref(BaseObject* p) { // intrusive_ptr support
++p->ref_count_;
}
void intrusive_ptr_release(BaseObject* p) { // intrusive_ptr support
if(!--p->ref_count_)
delete p;
}
struct Object1 : BaseObject {
virtual void accept(Visitor& v) { v.visit(*this); } // Visitor's double dispatch
virtual void getSomeCommonProperty() { printf("%s\n", __PRETTY_FUNCTION__); }
void getSomeSpecificProperty() { printf("%s\n", __PRETTY_FUNCTION__); }
};
template<class T, class Functor>
struct FunctorVisitor : Visitor {
Functor f_;
FunctorVisitor(Functor f) : f_(f) {}
void visit(T& t) { f_(t); } // apply to T objects only
template<class P> void operator()(P const& p) { p->accept(*this); }
};
template<class T, class Functor>
FunctorVisitor<T, Functor> apply_to(Functor f)
{
return FunctorVisitor<T, Functor>(f);
}
int main()
{
typedef boost::intrusive_ptr<BaseObject> BaseObjectPtr;
typedef std::vector<BaseObjectPtr> Objects;
Objects objects;
objects.push_back(BaseObjectPtr(new BaseObject));
objects.push_back(BaseObjectPtr(new Object1));
for_each(
objects.begin()
, objects.end()
, boost::bind(&BaseObject::getSomeCommonProperty, _1)
);
for_each(
objects.begin()
, objects.end()
, apply_to<BaseObject>(boost::bind(&BaseObject::getSomeCommonProperty, _1))
);
for_each(
objects.begin()
, objects.end()
, apply_to<Object1>(boost::bind(&Object1::getSomeSpecificProperty, _1))
);
}
Output:
$ ./test
virtual void BaseObject::getSomeCommonProperty()
virtual void Object1::getSomeCommonProperty()
virtual void BaseObject::getSomeCommonProperty()
void Object1::getSomeSpecificProperty()
I think you should go for option 1 but use a static cast instead. After all the derived collection knows the type of the member variable for sure.
This answer explains it very well.
Id use nested adapter as in below example. You have to specialize it for every class you want to do a fancy update
!The example has memory leak - allocated A, B, Q objects are not deleted!
#include <iostream>
#include <vector>
#include <algorithm>
class Q
{
public:
virtual void Foo()
{
std::cout << "Q::Foo()" << std::endl;
}
};
class A
{
public:
virtual void Foo()
{
std::cout << "A::Foo()" << std::endl;
}
};
class B : public A
{
public:
virtual void Foo()
{
std::cout << "B::Foo()" << std::endl;
}
virtual void BFoo()
{
std::cout << "B::BFoo()" << std::endl;
}
};
template <typename ElementType>
class C
{
public:
template <typename T>
void add(T* ptr){m_Collection.push_back(std::unique_ptr<Adapter>(new ConcreteAdapter<T>(ptr)));}
void updateAll()
{
std::for_each(m_Collection.begin(), m_Collection.end(), [&](std::unique_ptr<Adapter> &adapter)->void{adapter->update();});
}
private:
class Adapter
{
public:
virtual ElementType* get() = 0;
virtual void update(){get()->Foo();}
};
template <typename T>
class ConcreteAdapter : public Adapter
{
public:
ConcreteAdapter(T* ptr) : m_Ptr(ptr){}
virtual T* get(){return m_Ptr;}
protected:
T* m_Ptr;
};
template <>
class ConcreteAdapter<B> : public Adapter
{
public:
ConcreteAdapter(B* ptr) : m_Ptr(ptr){}
virtual B* get(){return m_Ptr;}
virtual void update()
{
get()->Foo();
get()->BFoo();
}
private:
B* m_Ptr;
};
std::vector<std::unique_ptr<Adapter>> m_Collection;
};
int main()
{
C<A> c;
c.add(new A());
c.add(new B());
//c.add(new Q()); //error - correct
c.updateAll();
return 0;
}
Maybe this will do the trick here ?
class CollectionManipulator {
public:
void someCommonTask(BaseCollection& coll) {
for(unsigned int i = 0; i < coll.size(); i++)
someCommonTask(coll.getObj(i));
}
private:
void someCommonTask(BaseObject*); // Use baseObjects
};
class BaseCollection {
friend class CollectionManipulator;
private:
virtual BaseObject* getObj(unsigned int) = 0;
virtual unsigned int size() const = 0;
};
class Collection1 : public BaseCollection {
vector<Object1*> objects;
public:
virtual void addObject() {
Object1* obj = new Object1;
objects.push_back(obj);
baseObjects.push_back(obj);
}
void someSpecificTask(); // Use objects, no need of dynamic_cast<>
private:
BaseObject* getObj(unsigned int value) {
return object[value];
}
unsigned int size() const {
return objects.size();
}
}
If you want abstract your container in Collection1 (like using list instead using vector), to use it in Manipulator, create an abstract iterator...
I think the solution should be a mix of factory method pattern and template method pattern. Take a look at those to refine your design.
Edit: Here is a sample code. GenericProduct is the BaseObject, it provides two methods, one that is general (though it could be overridden), and a specific method which does nothing, it is not a pure virtual so this class can be instantiated. SpecificProduct is a subclass, which implements the specific method in some way.
Now, Factory class is an abstract class that defines an interface for creating specific products by specific factories, it defines a pure virtual method createProduct which creates the product. Two concrete factories are created GenericFactory and SpecificFactory which create specific products.
Finally, the Consumer abstract class (which corresponds to BaseCollection in your code), it defines a pure virtual method for creating a factory createFactory in order to force subclasses to create their own concrete factories (and hence, the correct products). The class also define a method fillArray (prototype pattern) to fill the array with products created by the factory.
#include <iostream>
#include <vector>
using namespace std;
class GenericProduct{
public:
virtual void getSomeCommonProperty()
{
cout<<"Common Property\n";
}
virtual void getSomeSpecificProperty()
{
cout<<"Generic Has Nothing Specific\n";
}
};
class SpecificProduct : public GenericProduct{
public:
virtual void getSomeSpecificProperty()
{
cout<<"Specific Product Has a Specific Property\n";
}
};
class Factory
{
public:
virtual GenericProduct* createProduct() = 0;
};
class GenericFactory : public Factory
{
public:
virtual GenericProduct* createProduct()
{
return new GenericProduct();
}
};
class SpecificFactory : public Factory
{
public:
virtual GenericProduct* createProduct()
{
return new SpecificProduct();
}
};
class Consumer
{
protected:
vector<GenericProduct*> gp;
Factory* factory;
protected:
virtual void createFactory() = 0;
public:
void fillArray()
{
createFactory();
for(int i=0; i<10; i++)
{
gp.push_back(factory->createProduct());
}
}
virtual void someCommonTask()
{
cout<<"Performaing a Common Task ...\n";
for(int i=0; i<10; i++)
{
gp[i]->getSomeCommonProperty();
}
}
virtual void someSpecificTask()
{
cout<<"Performaing a Specific Task ...\n";
for(int i=0; i<10; i++)
{
gp[i]->getSomeSpecificProperty();
}
}
};
class GenericConsumer : public Consumer
{
virtual void createFactory()
{
factory = new GenericFactory();
}
};
class SpecificConsumer : public Consumer
{
virtual void createFactory()
{
factory = new SpecificFactory();
}
};
int main()
{
Consumer* c = new GenericConsumer();
c->fillArray();
c->someCommonTask();
return 0;
}