2

I would like to write down a set of classes in which there are:

  • a pure virtual class that wraps an object of any kind and the relate getter for it.
  • one or more classes for every kind of object I need, extending the virtual one and overriding the getter in order to specialize it.

A template class solution for the wrapper seems to fit the case but I have to use it in two different contexts:

  • the first one is not aware of wrapper implementations. In this case I should declare a Wrapper<AnyObj> var; with AnyObj standing for any class name (like ? in Java). As far as I know, you can't do this in c++.
  • the second one is restricted to a particular wrapper implementation. In this case I need the getter to return the wrapped object with the exact type (rather than downcasting it).

If I'm right I cannot use a template class and, moreover, the wrapper won't have a protected: T* wrappedObject member.

I don't know if I'm stuck in the Java approach, wrongly thinking from the beginning, or missing something.

Any suggestion is appreciated.

curiousguy
  • 8,038
  • 2
  • 40
  • 58
ruphus
  • 163
  • 1
  • 13
  • 1
    "As far as I know, you can't do this in c++." .. You mean something like this: `template < typename T > class Wrapper { public: Wrapper(const T& t) : m_obj(t) {} T* getObj() { return &m_obj; } protected: T m_obj; };`? Then to derive it (as you mention): `class IntDerived : public virtual Wrapper { public: IntDerived(int v) : Wrapper(v) {} };` .. But, `pure virtual class` and `one or more classes for every kind of object I need` coupled with `templates` sounds like you've got other design concerns. As another comment said, what problem are you trying to solve with this approach? – txtechhelp Mar 20 '16 at 04:43
  • There is no such thing as a "pure virtual class". Maybe you meant abstract class? – curiousguy Mar 21 '16 at 01:32
  • @txtechhelp thank you for the comment. The code you posted is the solution I tried before but what I still can't do is to use the syntax `Wrapper var = specializationContext.getWrapper();` when I need it in the first of the two contexts i mentioned. I found that I could use the `Wrapper<> var;` form if I declared `template ` class Wrapper ...` but it's like using a `` specialization (not the generic) and it could be dangerous. I wrote the question because I know that the template pattern could not be suitable for this case. – ruphus Mar 21 '16 at 07:50
  • I did not give you anything. You're assuming too much. I have not voted on this question. – Sam Varshavchik Mar 21 '16 at 12:29
  • @SamVarshavchik You're right, my apologies – ruphus Mar 21 '16 at 17:58

0 Answers0