1

Let's say I have the following:

class Base 
{
  protected:
    Base() { }
};

class A : public Base
{
};

class B : public Base
{
};

Now suppose I do this with a template:

TemplatedClass<Base> *generic = new TemplatedClass<A>();

It doesn't work, and I believe I understand why, but I'd like to know if I can do something equivalent. I have several template specializations of the form

typedef TemplatedClass<A> ASpec;
typedef TemplatedClass<B> BSpec;
typedef TemplatedClass<C> CSpec;

I have a single variable whose type I'd like to defer until runtime, so that I can dynamically assign it like

if(condition1)
  generic = new ASpec();
else if(condition2)
  generic = new BSpec();

Is there any way to go about this? I don't have the ability to change the fact that the classes are templated and not inheriting from a base class, or I'd just do that.

4
  • where is TemplatedClass defined?
    – stardust
    Apr 18, 2013 at 18:07
  • Of course it doesn't work. There is no template named TemplatedClass. Nobody's going to guess what this template does. Apr 18, 2013 at 18:08
  • TemplatedClass represents a made-up class template for the purposes of this question. Pretend for a moment that I replaced TemplatedClass with std::vector. My question is less about the specific code I wrote and more about whether or not the assignment would ever be valid for any template specialization.
    – automatom
    Apr 18, 2013 at 18:22
  • For std::vector, no. For some other template, maybe. It depends on the template. Apr 18, 2013 at 18:24

2 Answers 2

1

This is not possible in C++. The fact that A derives from Base doesn't mean that TemplatedClass<A> derives from TemplatedClass<Base>.

See this Stack Overflow post for alternatives: Conversion from STL vector of subclass to vector of base class

0
0

You can derive TemplatedClass<T> from TemplatedClass<Base>, either by specialising if for Base, or by providing a dummy class like this:

struct Dummy {};

template <typename T>
struct BaseClass<T> {
  typedef TemplatedClass<Base> Type;
};

template <>
struct BaseClass<Base> {
  typedef Dummy Type;
};

template <typename T>
struct TemplatedClass : BaseClass<T>::Type
{
  //...
};
1
  • Thanks, Angew. If I were able to change things at that level, this is the way I'd go, but I have to work with TemplateClass as it's been defined.
    – automatom
    Apr 18, 2013 at 18:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.