Auto Function with if Statement will not return value

I created a template and an auto function that compares 2 values ​​and returns the smallest. This is my code:

#include <iostream>
using namespace std;

// Template with a value returning function: PrintSmaller
template <typename T, typename U>
auto PrintSmaller(T NumOne, U NumTwo) {
    if (NumOne > NumTwo) {
        return NumTwo;
    }
    else {
        return NumOne;
    }
}

int main() {

    int iA = 345;
    float fB = 23.4243;

    cout << PrintSmaller(iA, fB) << endl;
    cout << PrintSmaller(fB, iA) << endl;

    return 0;
}

But it will not compile, I get this error on VS 2015: Error C3487 'int': all returned expressions must be output in the same type: earlier it was a 'float'

However, if I delete the if statement and write the PrintSmaller function like this, it will work without problems:

auto PrintSmaller(T NumOne, U NumTwo) {
return (NumOne < NumTwo ? NumOne : NumTwo);
}

What is the difference? and why the first code will not compile? Thank.

+4
source share
3 answers

return. return , return, . return , , , .

?: , . .

, return. , , .

+8

++ 11, , ++ 11. , ++ 11 , ( ) .

?: , , if-else - .

++ 14, , , .

0

(2017-12-06) MSVC. VS 15.5 .

    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 an explicit return type will choke on 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 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, this gcc / clang problem pair has no problems with the above. Try some online ideal that you prefer to convince yourself ...

0
source

Source: https://habr.com/ru/post/1666171/


All Articles