gpt4 book ai didi

c++ - 自动无法推断出正确的返回类型

转载 作者:可可西里 更新时间:2023-11-01 18:04:19 25 4
gpt4 key购买 nike

我声明了一个函数,该函数返回参数化模板类的 shared_ptr 类型的 auto 类型。在我的例子中,如果我添加“else”条件,编译器会提示我类型不完整。使用相同的函数签名,它可以在一种情况下正常工作。任何使编译器满意的优雅解决方案。

auto getCustomerDataSource(ptree const &node){
const auto dataSource = node.get<std::string>("<xmlattr>.Type");
const auto sourceString = node.get<std::string>("SourceString");
if (dataSource == "File") {
return std::make_shared<CustomerData<CFileSource>>(sourceString);
} else if (dataSource == "DataBase") {
return std::make_shared<CustomerData<CDatabaseSource>>(sourceString);
}
}

最佳答案

您的代码违反了 C++ 标准中的以下规则 [dcl.spec.auto.8] :

If a function with a declared return type that contains a placeholder type has multiple non-discarded return statements, the return type is deduced for each such return statement. If the type deduced is not the same in each deduction, the program is ill-formed.


CFileSource & CDatabaseSource are two possible algorithms that user can pick one to build CustomerData object.

一个问题是您正试图对在运行时决定的事物使用静态多态性(模板)。因此,更好的解决方案是将您的算法作为具有公共(public)基础的多态类提供。然后,您可以将指向 base 的指针作为 CustomerData 的成员变量,它不再需要是模板。

关于c++ - 自动无法推断出正确的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56059097/

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