auto Function with if Statement won't return a value

前端 未结 3 1850
醉话见心
醉话见心 2021-01-19 18:11

I made a template and an auto function that compare 2 values and return the smallest one. This is my code:

#include 

        
相关标签:
3条回答
  • 2021-01-19 18:42

    A function can only have a single return type. Using return type deduction means that it will be deduced based on the type of the expression in the first return statement the parser sees. If later return statements do not return expressions of the same type, then the function is considered to be self-contradictory and thus ill-formed.

    In the second case, the ?: determines the type of the expression based on a common type determined based on the second and third sub-expressions. The two sub-expressions will be converted to this common type.

    That's different from how return type deduction works. If you intend for your first case to work, then you need to explicitly convert the returned value to the desired return type.

    0 讨论(0)
  • 2021-01-19 18:57

    Until yesterday (2017-12-06) this was not compiling under MSVC. But after VS 15.5 update it does.

        auto msvc_does_compile = [](auto _string)
         {
          using string_type = decltype(_string);
          return std::vector<string_type>{};
         };
       /*
        OK since VS 2017 15.5 update
       auto vec1 = msvc_does_compile( std::string{} );
       */
    

    Adding explicit return type will choke MSVC , but not gcc/clang as usual:

    auto msvc_does_not_compile = [](auto _string)
        // explicit return type makes msvc not to compile
        -> std::vector< decltype(_string) >
      {
        using string_type = decltype(_string);
        return std::vector<string_type>{};
      };
    

    And something of the same but simpler will be stopped even at the IDE stage:

        auto msvc_ide_does_not_allow = []( bool wide )
        {
           if (wide)
            return std::vector<std::string>();
    
            return std::vector<std::wstring>();
        };
    

    Yes, again that troublesome pair gcc/clang has no problems with the above. Try which ever online ide you prefer to convince yourself...

    0 讨论(0)
  • 2021-01-19 18:59

    As you have asked this question with the c++11 marker, I suppose you are using C++11. Unfortunately, the C++11 standard states that auto-type deduction (also for lambdas) is limited to a single statement.

    As the ?: operator is an expression instead of a statement, this will work while the if-else is a statement and doesn't meet the requirements.

    If you would compile this code with the C++14 standard, you will see that it should compile both cases as this limitation was removed.

    0 讨论(0)
提交回复
热议问题