c++ design: inheritance and returning opaque handles -


i have 2 interfaces looks this:

class ithing {     ...     virtual ihandle* gethandle(void) = 0;     virtual void usehandle(ihandle *handle) = 0; };  class ihandle { ... } 

i want users able implement ithing , ihandle. example, if user creates mything , myhandle, gethandle should return pointer myhandle, user can later use in usehandle.

this work, don't design because multiple implementations of ihandle can mixed between implementations of ithing. in usehandle, users need explicitly downcast implementation of ihandle. there more type-safe way this?

i'm not quite sure of want design. here thoughts hope helpful.

the basic principle classes publicly derived ithing indeed ithing. eveything can ithing, can mything, including getting ihandle.

there's no design issue, long ihandle derivates obey same principle. means things shouldn't make assumptions specific handles , vice versa.

if make use in implementation of myhandle of assumptions it's linked mything (or vice versa), you'll troubles describe. in fact use dependency not expressed in class definition. yes, you'll have use downcast. it's unconfortable, because reveals desing issue.

as classes polymorphic, can limit downcasting risks checking nullptr dynamic_cast. workaround, not design improvement.

alternatively consider templates. link related types @ compile time. you'll gain on type safety, you'll loose flexibility of runtime polymorphism. 1 example approach:

template <class ih> class ithing  {    public:     virtual ih* gethandle(void) =0;     virtual void usehandle(ih *handle) =0; };  class myhandle {  };  // keep simple,   class mything: public ithing<myhandle> {}; // instantiation specific handle  int main() {     mything i;      myhandle *h;     h = i.gethandle();      ...  } 

the constraint in example, don't mix different ithings using different handles.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -