lundi 27 mai 2019

C++14: auto return type of a function which can return an object of sibling

I have two classes which are inheriting from class Base

class Derived_1:public Base
{
  public:
     getSomeFunc();
};

class Derived_2:public Base
{
  public:
     getSomeFunc();
};

Now what I want to write a function which takes base class pointer object and after dynamic casting finding the appropriate child and returns it so that we can call right version of getSomeFunc()

I tried to write

auto getChild(Base* ptr)
{
  Derived_1 * p = dynamic_cast<Derived_1*>(ptr)
  if(p)
  {
    return p;
  }
  else
  {
      Derived_2 * q = dynamic_cast<Derived_2*>(ptr)
      if(q)
      {
        return q;
      }
     else
     { 
        // some handling to avoid bugs!!
     }
  }

But It does not get compiled. Any way to serve my requirement.

Edit ----------------------------------
Error from compiler is - incorrect deduction of 'auto'. Compile is gcc

Aucun commentaire:

Enregistrer un commentaire