2

I have the following situation:

basestuff is a shared library that implements my base model... derivedstuff is different for every implementation and represent the application objects. utilitystuff is a shared library with utility functions.

Here is the code:

namespace basestuff {
    class Base {}  // Base model
    virtual std::unique_ptr<Base> createNew(); // Factory 
}

namespace derivedstuff {
    class Derived : public Base {}  // Derived model

    // Factory implementation
    std::unique_ptr<basestuff::Base> createNew () {
          return str::unique_ptr<basestuff::Base>(new Derived);
    }
}


namespace utilitystuff {
    class Utility {
        /// get data and populate the vector element
        getDataList(std::vector<std::unique_ptr<basestuff::Base>> &list,
                    std::function<std::unique_ptr<basestuff::Base>()> &factory) 
        {
           for (...)
           {
               // ... Read data from somewhere and populate it...

               // create new element and add to vector
               std::unique_ptr<basestuff::Base> item = factory();

               list.push_back(std::move(item));           
           }
        };
    }
}

Here is the code I would like to have:

main()
{
    utilitystuff::Utility reader;
    derivedstuff::Derived dummy;

    std::vector<std::unique_ptr<derivedstuff::Derived> myClassList;
    reader.getDataList(&myClassList, dummy.createNew);
}

But this is not working, as unique_ptr needs to be from Base type and, even if I change it to Base, getDataList() does not accept the parameters as it differs from the Base class.

Is there a way to make use only of Derived on main() and make Base transparent to this level without the need to keep casting between one and another type ?

I´ve read the post here that is about casting, but I don´t wanna use casts here. I just wanna use the Derived in the above layer and let the underlying layer (Base) solve the problem.

Community
  • 1
  • 1
Mendes
  • 17,489
  • 35
  • 150
  • 263
  • 1
    What is `std::copy(item)`? I only know `std::move`. – Lingxi May 19 '15 at 13:26
  • `virtual std::unique_ptr createNew();` I assume you mean `Base`, and not `Basic`? And how is a `virtual` function supposed to work outside of a class definition? If you can make a sensible question out of this, I'll reopen it. – Praetorian May 19 '15 at 16:32

0 Answers0