Let's say I have two classes:
class A
{
public:
A* Hello()
{
return this;
}
}
class B:public class A
{
public:
B* World()
{
return this;
}
}
And let's say I have an instance of B
class like so:
B test;
If I call test.World()->Hello()
that would work fine.
But test.Hello()->World()
would not work since Hello()
returns A
type.
How could I make Hello()
return the type of B
? I don't want to use a virtual
function since we have over 20 different classes inheriting A
.
You can use CRTP, the curiously recurring template pattern:
template<class Derived>
class A {
public:
Derived* Hello() {
return static_cast<Derived*>(this);
}
};
class B : public A<B> {
public:
B* World() {
return this;
}
};
int main() {
B test;
test.World()->Hello();
test.Hello()->World();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With