【发布时间】:2015-04-20 09:54:27
【问题描述】:
我想询问协变返回类型和可能(非)应用程序。我以为我发现了一些新的设计模式,但遗憾的是它不起作用:(
让我们从一个例子开始:
// test.h
class B {public: virtual B* getSelf() {return this;} };
class D : public B { public: D* getSelf() {return static_cast<D*>(this);} };
void compute(B* something);
void compute(D* something);
// test.cpp
int main()
{
B* b = new D();
compute(b->getSelf()); // This calls compute(B*), not compute(D*)
}
知道为什么它不起作用吗?
PS 我为糟糕的格式道歉
编辑:当然,如果我在 main 中使用强制转换,它会正确调用 compute(D*)。
编辑 #2:我尽量避免切换 :)
【问题讨论】:
标签: c++ design-patterns covariance covariant