Search code examples
c++c++14auto

auto return type of a function which can return an object of sibling


I have two classes which are inheriting from class Base

struct Base
{
   virtual ~Base() = default;
};

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

class Derived_2:public Base
{
  public:
     void 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 1 ----------------------------------
Error from compiler is - incorrect deduction of 'auto'. Compile is gcc


Solution

  • This is almost certainly not what you want to do. Instead, use a virtual method:

    class Base {
    public:
        virtual void getSomeFunc() = 0;
        // ... etc etc ...
    };
    

    then, you could write:

    Base* ptr = get_a_base_instance_ptr_from_somewhere();
    ptr->getSomeFunc();
    

    In your code, you were trying to have auto have either the type of p or the type of q. But auto only has a single type. And a type which can accept both a pointer to Derived_1 and a pointer to Derived_2 is... yes, you guessed it: Base*.

    edit: If you are unable to change the Base, Derived_1 and Derived_2 class, you could consider using std::variant<Derived_1*, Derived_2*>, and using visitation to call the appropriate method for each of these types. If you haven't used variants before, see the CPP-reference page on std::variant. For information on how to write a visitor for use with a variant, see this SO question:

    How does std::visit work with std::variant?