Force Template to be Subclass

closed account (o1vk4iN6)
Is there any way to for a template argument to be inherited from a certain class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

template<class T>
class A {
   T t;

public:
   void foo(){ t.foo(); }
};

class B {
public:
   virtual void foo() = 0;
};

class C : public B {
public:   
   void foo();
};

class D {
   
};

A<C> ac; // ok

A<D> ad; // error


So I want the "T" in class "A" to be inherited from "B" so that it can use the "foo" function. There'd be an error since there's no foo function in class D but the message is kind of cryptic.
Last edited on
There is a big difference, but
1
2
3
class A{
  B *t;
};


error: 'class D' has no member named 'foo'
¿cryptic? However that error only appears if you try to use the foo method on the ad object.
Not possible
Last edited on
closed account (o1vk4iN6)
I could do some sort of assert in the constructor yah? Wouldn't help with any error messages unless it manages to compile somehow.

1
2
3
4
A()
{
   assert( dynamic_cast<B*>(&t) != NULL );
} 


I need to pass it as a template though since it needs to be able to construct/destruct the class. Otherwise ne555 I would do that. Thanks for the help.
Last edited on
since it needs to be able to construct/destruct the class
¿?
I don't understand what you mean.
¿how is that you can do that with templates?
Topic archived. No new replies allowed.