Re: C++ boxing
On 13/02/10 00:43, pfultz2 wrote:
Is there a way to box a type in c++ like this:
class Interface
{
public:
virtual void foo() = 0;
};
class A
{
public:
void foo();
};
And then I could box this type like this:
Interface * a = box_cast<Interface*>(new A());
There is no general way to do it, but for your specific interface you
can write something like:
template <Boxed>
class InterfaceBox : public Interface
{
std::auto_ptr<Boxed> m_boxed;
public:
InterfaceBox (Boxed* boxed) : m_boxed (boxed) {}
void foo () { m_boxed->foo (); }
};
template<Boxed>
Interface* box_interface (Boxed* boxed)
{
return new InterfaceBox<Boxed> (boxed);
}
....
Interface* boxed_a = box_interface (new A);
....
delete boxed_a;
....
Of course, you can decide to have a different memory management policicy
for the boxed type in case you still want to be able to use the A*
intance in other parts of the program, like using a shared_ptr, or a raw
pointer or whatever fits your needs. You could templatize that also...
JP
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]