c++ 퀴즈 퀴즈 퀴즈

  • #3761419
    76.***.207.158 651

    #include <bits/stdc++.h>
    using namespace std;

    template <class A, class B>
    auto funmin(A a, B b) -> decltype(a < b ? a : b)
    {
    return a < b ? a : b;
    }

    int main()
    {
    cout << funmin(4,3.44) << endl;
    cout << typeid(funmin(4,3.44)).name() << endl;

    cout << funmin(5.4, 3) << endl;
    cout << typeid(funmin(5.4, 3)).name() << endl;

    cout << funmin(5, 3) << endl; // No err mssg, but wrong
    cout << typeid(funmin(5, 3)).name() << endl; //

    cout << funmin(5.1, 3.2) << endl; //No err mssg, but wrong
    cout << typeid(funmin(5.1, 3.2)).name() << endl;

    return 0;
    }

    아웃풋: (컴파일러마다 조금 다를수는 있음.)
    3.44
    d
    3
    d
    0
    i
    0
    d

    funmin(a,b) 는 두 수중 작은 수를 리턴하는 간단한 함수.
    아웃풋이 보다시피, 같은 정수끼리나 같은 더블타입의 숫자끼리는 틀린 결과를 출력함. 이유가 뭘까? 뭐가 잘못되었는지 밝혀내는게 퀴즈. 쉬운 난이도는 아니므로 실력있는 사람만 도전할것.
    힌트 :decltype()

    • 72.***.167.222

      야! 재미 붙혔냐? 이런것 이제 그만 올려라! 우리가 니 가정교사냐?

    • 독거노인 172.***.75.197

      퐁퐁이 마누라들은
      주말이라 친구니 요가니 나가버리고
      퐁퐁이들은 이런거나 해야지 ㅎㅎ

      개발자=퐁퐁이 니덜 정말 말좀 해봐라 니덜 돈도 잘벌고 능력도 있는데
      퐁퐁이가 되서 놀던 여자랑 결혼후 경제권 등등 다뺏기고 퐁퐁이 노릇 하는 이유가 뭐냐?
      한국 동탄 삼성 퐁퐁이들이 아주 유명하다 동탄 신도시 유뷰녀들 아주 유명해

    • Jp 136.***.126.210

      ChatGPT response –

      This is a C++ program that defines a function template “funmin”, which compares two values of different types and returns the smaller of the two. The function uses the “decltype” keyword to determine the return type, which is the type of the expression “a < b ? a : b”. In the main function, the “funmin” function is called with various combinations of arguments, and the output of the function and the type of the returned value are displayed using the “cout” and “typeid” statements, respectively. The program has no errors, but the last 2 calls of the function funmin(5, 3) and funmin(5.1, 3.2) will not return the expected results due to the type of the arguments passed to the function.

    • ㅇㅇ 76.***.207.158

      ChatGPT response – 잘못된 이유는 설명을 못하고, 문제의 개요만 썸머리하고 있는듯 하군요.

    • jjjj 166.***.250.47

      decltype이 reference type를 리턴하기 때문에 a, b중 아닌 스택주소를 반환하게 되고 따라서 lifetime이 끝나기 때문에 int main 에서 읽는 시점에선 undefined behavior가 발생

      근데 여긴 이런 퀴즈 올리는 곳이 아니에용.. 좋은 회사에 오퍼는 보통 좋은 추천을 받아야 하는데 사회성 없으면 추천 못받음

      • hg 76.***.207.158

        레퍼런스 이용탓을 하는게 틀린대답은 아니지만 40점짜리 대답이다. 왜 타입이 다를때는 실행되고 타입이 같을때는 에러가 나오는지 제대로 설명을 해야지 뭉뚱구려가지고 말하면…

        글고 왠 갑자기 원글과 관련없는 추천서가 나오고 사회성이야기가 나오냐?

    • J 80.***.119.87

      std::is_same_v<A, B> 인 경우 decltype 표현이 레퍼런스 (A&) 타입으로 evaluate 되고 funmin 의 리턴 타입도 A 가 아니라 A& 이 됨.
      종료된 서브루틴의 로컬 변수 레퍼런스를 cout 에 사용하는 셈이 되어 출력값의 올바름을 보장할 수 없게 됨.

      arithmetic operator 에 int 와 double 이 섞인 경우는 int 가 double로 implicit conversion 되는데 그러면 int 인 경우는 레퍼런스를 그대로 사용할 수 없게 되므로 decltype 표현이 double 이라는 non-reference type 이 되므로 결과값이 return by value 가 되어 올바름에 문제가 없음. 실무에서는 std::min 처럼 A==B==return_type 를 강제해서 사용자가 인자를 직접 원하는 방식으로 변형해 넣게끔 하는 게 버그 방지에 좋음.

      언어 표준의 코너 케이스를 시험하는 퀴즈고, 예로 든 funmin 함수도 의도하지 않은 타입 변환이나 dangling 레퍼런스를 발생시킬 수 있는 위험한 디자인이므로 brain teaser 에 가까워 보임.