【发布时间】:2011-02-14 04:58:01
【问题描述】:
我显然已经在 Java 领域停留了太久...是否可以执行以下 Java 代码的 C++ 等效项:
interface Foo {}
class Bar implements Foo {}
static List<Foo> getFoo() {
return new LinkedList<Foo>();
}
static List<Bar> getBar() {
return new LinkedList<Bar>();
}
List<? extends Foo> stuff = getBar();
其中 Foo 是 Bar 的子类。
所以在 C++ 中......
std::list<Bar> * getBars()
{
std::list<Bar> * bars = new std::list<Bar>;
return bars;
}
std::list<Foo> * stuff = getBars();
希望这是有道理的......
【问题讨论】:
-
你确定这在 Java 中有效吗?因为我刚刚检查过,并不是因为 Java 不支持协变泛型。此外,这只有在
Bar是Foo的子类时才有意义。 -
正确。我的错。我现在已经更正了代码 sn-p。
标签: c++ generics list templates stl