gpt4 book ai didi

c++ - 如何根据条件在不拼接的情况下向上转换该对象?

转载 作者:行者123 更新时间:2023-12-01 22:51:46 24 4
gpt4 key购买 nike

我偶然发现了一个可能微不足道的问题。我要调用doSomething()AbstractParser 的实例上,其中所述实例属于派生类 FooParserBarParser 。是其中之一取决于用户提供的运行时参数。代码的其余部分应该只有一种方法来访问父级 AbstractParser目的。见下文。

AbstractParser& myParser;   // Error: can't have a reference to nothing
if(some_condition){
FooParser parser = FooParser();
myParser = parser;
}else{
BarParser parser = BarParser();
myParser = parser;
}
// lots of code with other things ...
parser.doSomething();

根据条件,我想使用myParser (或指向它的指针)超出 if 的范围 block ,和 myParser应该表现为适当的派生对象。我想避免复制我的对象和(如果可能)移动构造函数。没有条件我也能做到

FooParser parser = FooParser();
AbstractParser &myParser = parser; // upcast without slicing
// lots of code with other things ...
parser.doSomething();

而且它会干净、优雅、向上,而不需要切片 parser 。我现在不知道该怎么做。

如何在不复制创建的对象或使它们超出范围的情况下向上转换派生解析器?我需要创建 std::unique_ptr<AbstractClass>并使用make_unique<FooParser>()里面if ?或者我应该使用一个返回派生类引用的函数?或者static_cast<AbstractClass> ?还是我把这个问题过于复杂化了?

最佳答案

简单的解决方案是使用unique_ptr:

std::unique_ptr<AbstractParser> myParser;
if (some_condition)
myParser = std::make_unique<FooParser>();
else
myParser = std::make_unique<BarParser>();

myParser->doSomething();

如果你想避免堆分配,你必须使用std::variant之类的东西,但它不太方便:

std::variant<std::monostate, FooParser, BarParser> var;
AbstractParser *myParser;
if (x)
myParser = &var.emplace<FooParser>();
else
myParser = &var.emplace<BarParser>();

myParser->doSomething();

关于c++ - 如何根据条件在不拼接的情况下向上转换该对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60193975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com