jeudi 28 avril 2016

Is it possible to check a condition on a derived class where the base class only in known?

I would like to be able to check whether a certain condition is true or not on an object of some Derived type, which in the local context is only known through its Base type.

The condition to be checked needs the Derived type.

One possible way of doing this is the following.

Define the classes

class Base {
//...  
public:
  using Condition = std::function<bool(const Base*)>;
  bool check(const Condition&);
}

class Derived : public Base {
//...
public:
  int index() const { return index;}
private:
  int index;
}

and suppose we have a Derived-aware context, where I can encapsulate the the Derived-specific condition in a lambda function. We can then dispatch the Condition functor to the context where it is going to be needed:

 //context where Derived class is known

 int idx = 1;

 auto derivedCondition = [idx](const Base* obj) {
    Derived* derivedObj = dynamic_cast<const Derived*>(obj); 
    if (derivedObj)        
      return (derivedObj->index() == idx);
    return false;
 };

 // dispatch condition to an external context where it will be used, this context is not aware of Derived
 useConditionElsewhere(derivedCondition);

with

 void useConditionElsewhere(Condition condition) {

    //context where only base class is known
    Base* baseObj;
    //...

    bool checked = baseObj->check(condition);
    //..
 }

The above achieves what I need.

My question is: is it possible to do this without casting?

Aucun commentaire:

Enregistrer un commentaire