假设我有两个类:
class A
{
public:
A* Hello()
{
return this;
}
}
class B:public class A
{
public:
B* World()
{
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
让我们说我有一个B像这样的类的实例:
B test;
Run Code Online (Sandbox Code Playgroud)
如果我打电话test.World()->Hello()说那会很好.但是test.Hello()->World()因为Hello()返回A类型不起作用.
我Hello()该如何归还B?我不想使用virtual函数,因为我们有超过20个不同的类继承A.
mfo*_*ini 18
您可以使用CRTP,这是一个奇怪的重复模板模式:
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();
}
Run Code Online (Sandbox Code Playgroud)