Re: Would templates make this simpler?
On Fri, 27 Apr 2007 10:07:25 -0700, "David Ching"
<dc@remove-this.dcsoft.com> wrote:
I do not think templates would make this any easier, but thought I would
verify with the experts here.
FWIW, you'll find far more template expertise in
microsoft.public.vc.language and far, far more in comp.lang.c++.moderated.
I have a base class and 2 derived ones:
class CBase
{
public:
virtual void Method1();
};
class CDerived1 : public CBase
{
public:
virtual void Method1();
};
class CDerived2 : public CBase
{
public:
virtual void Method1();
};
Now I need to instantiate the correct one based on a flag:
CBase *CreateTheClass(bool flag)
{
if (flag)
return new CDerived1;
else
return new CDerived2;
}
Could I get rid of the if() if I just created something like
return new CBase<flag>;
It's not going to work since templates are a compile-time mechanism, and
flag isn't known until run-time. Since you want to create CDerived
instances, it's not the right approach anyway. I guess the closest you
could come using templates is to do something like this:
template<bool X> class Derived;
template<>
class Derived<true> : public CBase
{
...
};
template<>
class Derived<false> : public CBase
{
...
};
CBase* p1 = new Derived<true>;
CBase* p2 = new Derived<false>;
But that still doesn't solve your problem, because your bool value isn't
known until run-time.
--
Doug Harrison
Visual C++ MVP