Inheriting from a template

I'm trying to inherit methods that return the object but I'm having some problems understanding how to do so. After doing some extensive search (at least it felt extensive) I figured inheriting from template would be the best thing to do. I have this simplified code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
template <typename T>class class1
{
  protected:
    
  public:
    T *inst (void) {return this;}
};

class class2 : public class1<class2>
{
  public:
    char c;
};

int main (int argc, char *argv[], char *env[])
{
  class2 *test1 = new class2;
  class2 *test2;
  
  test2 = test1->inst();
}

And it does not compile, I get this error:
1
2
3
test3.cc: In member function `T* class1<T>::inst() [with T = class2]':
test3.cc:22:   instantiated from here
test3.cc:8: error: invalid conversion from `class1<class2>* const' to `class2*' 


I don't know what I'm doing wrong here. Pretty much, what I want to end up with is every class that inherits from "class1" to respond to "init()" and have the correct object type returned.

Thanks
Last edited on
What you want to do is what casting is for. Templates do not help you here (and in fact they complicate things and make it less functional and worse)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class class1
{
 // stuff
};

class class2 : public class1
{
public:
  char c;
};

int main()
{
  class1* test1 = new class2;
  class2* test2;

  test2 = dynamic_cast<class1*>(test1); // performs runtime checks to make sure cast is valid
  test2 = static_cast<class1*>(test1);  // does not do runtime checks.  You better be sure!

  return 0;
};


The reason why templates are no good here:

1) each instance of a template class is a different class. IE: class1<class2> would be a different class from class1<class3>. And therefore you cannot have simple class1* pointers -- but would need class1<class2>* pointers (which is silly, since you might as well just use a class2* pointer.

2) Your 'inst' function would be trying to downcast to type 'T*'. This can never be implicit (ie, you can't just return "this", you'd have to downcast "this" with either static_cast or dynamic_cast.
Topic archived. No new replies allowed.