自动无法推断出正确的返回类型
auto fail to deduce correct return type
我已经声明了一个函数auto
该函数返回参数化模板类shared_ptr
的类型。就我而言,如果我添加"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] 中的以下规则:
如果具有包含占位符类型的声明返回类型的函数具有多个未丢弃的
return
语句,则为每个此类return
语句推导返回类型。如果推导的类型在每个推导中都不相同,则程序格式不正确。
CFileSource
和CDatabaseSource
是两种可能的算法,用户可以选择一种来构建CustomerData
对象。
问题是您正在尝试将静态多态性(模板)用于在运行时决定的内容。因此,更好的解决方案是将您的算法作为具有公共基础的多态类提供。然后,你可以做一个指向 base 的指针,作为CustomerData
的成员变量,它不再需要是模板。
使用auto
时,对于程序可能采用的每个可能路径,函数的推导返回类型必须相同。在这里,您的函数有 3 种不同的可能返回类型:
- 执行第一个
if
主体:std::shared_ptr<CustomerData<CFileSource>>
- 执行第二个
if
体:std::shared_ptr<CustomerData<CDatabaseSoruce>>
- 两者都不执行:
void
这是无效的。
CFileSource和CDatabaseSource是两种可能的算法 可以选择一个来构建客户数据对象。你可以考虑 getCustomerDataSource作为返回shared_ptr的工厂方法。 客户数据<>基于传递的参数。
看来您的误解如下:同一模板的两个实例化之间除了它们是同一模板的实例化之外,没有任何关系。
考虑:
template<typename T>
struct Foo{};
??? bar(bool x) {
if (x) return Foo<int>();
return Foo<double>();
}
没有一种类型可以代替???
因为Foo<int>
和Foo<double>
没有任何关系。它们是同一时间的实例,但仅此而已。
也许你想要这样的东西:
struct Moo_base {};
template <typename T>
struct Moo : Foo_base {};
因为现在Moo<int>
和Moo<double>
都可以通过std::shared_ptr<Moo_base>
传递。
- 在实例化之前推断函数模板的返回类型
- "auto"推断出 hashtable_policy.h 中的错误类型
- 无法推断返回类型的模板参数
- 推断成员函数的返回类型
- 三元运算符 '?:' 在 4.9.0 之前的 GCC 版本中推断出不正确的类型?
- 为什么"return (str);"推断出与C++中的"return str;"不同的类型?
- 模板化函数以从输入参数推断返回类型 stl-container
- 为什么编译器不能从返回类型中推断出模板参数?
- C++推断要隐式调用的模板函数返回类型
- 从参数的返回类型推断类型
- 将返回类型推断为模板参数类型方法
- 如何允许编译器推断出正确的返回类型以进行模板get函数
- 自动无法推断出正确的返回类型
- 如何使模板化运算符推断出正确的返回类型
- 编译器无法推断出要返回的模板类型
- C++基于输入参数的返回类型推断
- 从函数参数的返回类型推断函数返回类型
- 如何让编译器推断出c++ 11中模板化方法的返回类型
- 类模板化成员函数和返回类型推断
- 返回类型推断:首选哪种方法