Another template question

What I want to do is have Init in a base template class and have it return its derived class. The code below doesn't work, but it illustrates what I wish to achieve.

Is there a way to accomplish this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
template <class T>
class A{
  T *Init(){ return this; }
};

class B : public A<B>
{
public:
 void Check(){}
};

int main(){
 B Test;
 Test.Init()->Check();
 return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
template<class T>
class A {
public:
    T *Init() {
        return static_cast<T*>(this);
    }
};

class B: public A<B> {
public:
    void Check() {}
};

int main() {
    B Test;
    Test.Init()->Check();
    return 0;
}
This sounds a bit anti-polymorphic.

What are you trying to do?
closed account (1yR4jE8b)
I'm curious too, I don't really see the point of doing this.
Some of my classes uses a prototype pattern that uses static interfaces to allocate.

The prototype interface is pretty much the same across different types. So, I made it template. Able to return its derived type rather than itself.

Inheritance for the interface, template for the allocation.
Last edited on
Topic archived. No new replies allowed.