Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto fail to deduce correct return type

Tags:

c++

c++14

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);
   }
 }
like image 568
Aditya Kumar Avatar asked May 09 '19 12:05

Aditya Kumar


2 Answers

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 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.

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.

like image 64
Daniel Langr Avatar answered Nov 05 '22 22:11

Daniel Langr


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:

  1. first if body is executed: std::shared_ptr<CustomerData<CFileSource>>
  2. second if body is executed: std::shared_ptr<CustomerData<CDatabaseSoruce>>
  3. neither is executed: void

This is not valid.

like image 41
Ayxan Haqverdili Avatar answered Nov 05 '22 21:11

Ayxan Haqverdili