I have declared a function which returns auto
type of a shared_ptr
of parameterized template class. In my case compiler complains me about incomplete type if I add "else" condition. With same function signature it works fine with one condition. Any elegant solution to make the compiler happy.
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);
}
}
Your code violates the following rule from the C++ Standard [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 suchreturn
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 buildCustomerData
object.
A problem is that you are trying to use a static polymorphism (templates) for something that is decided at runtime. A better solution would therefore be to provide your algorithms as polymorphic classes with a common base. Then, you might make a pointer to base being a member variable of CustomerData
, which won't need to be a template any longer.
When auto
is used, the deduced return type for the function must be the same for every possible path the program may take. Here your function has 3 different possible return types:
if
body is executed: std::shared_ptr<CustomerData<CFileSource>>
if
body is executed: std::shared_ptr<CustomerData<CDatabaseSoruce>>
void
This is not valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With