728x90
반응형

C++17에서 std::unary_functionstd::binary_function 가 제거된 이유

1. 개요

  • std::unary_functionstd::binary_functionC++98 표준에서 함수 객체를 만들 때 인자 및 반환 타입 을 명시적으로 제공하기 위해 사용되던 구조체입니다.
  • 그러나 C++17 표준부터는 이 두 기능이 제거되었습니다.
  • 이는 더 이상 필요하지 않기 때문이며, 현대 C++auto, decltype, std::function, 람다 등을 통해 타입 추론과 함수 객체 작성이 더 직관적이고 강력해졌습니다.


2. 제거 이유 요약

  • 불필요한 중복 : 현대 C++은 타입 추론 기능이 강력해 굳이 typedef 제공이 필요 없음
  • 표준 라이브러리 리팩토링 : std::plus, std::less 등도 해당 기반을 사용하지 않고 구현
  • 메타 프로그래밍 개선 : decltypestd::invoke 등이 등장하면서 복잡함이 사라짐


3. C++98 예제

  • cpp

      #include <iostream>
      #include <functional>
      
      // std::unary_function 사용 예제
      // std::unary_function 는 함수 인자 1개만 사용 가능
      struct PrintInt : public std::unary_function<int, void> { // 인자 (int), 반환값 void
          void operator()(int x) const {
              std::cout << "값: " << x << std::endl;
          }
      };
      
      // std::binary_function 사용 예제  
      // std::binary_function는 함수 인자 2개만 사용 가능
      struct Add : public std::binary_function<int, int, int> { // 인자 (int, int), 반환값 void
          int operator()(int a, int b) const {
              return a + b;
          }
      };
      
      int main() {
          PrintInt print;
          print(10);
      
          Add add;
          std::cout << "합: " << add(3, 4) << std::endl;
      
          return 0;
      }
    


4. C++17 이후 예제

  • cpp

      #include <iostream>
      #include <functional>
      
      // std::unary_function, std::binary_function 없이 작성
      struct PrintInt {
          void operator()(int x) const {
              std::cout << "값: " << x << std::endl;
          }
      };
      
      struct Add {
          int operator()(int a, int b) const {
              return a + b;
          }
      };
      
      int main() {
          PrintInt print;
          print(10);
      
          Add add;
          std::cout << "합: " << add(3, 4) << std::endl;
      
          // 또는 람다 함수 사용
          auto add_lambda = [](int a, int b) { return a + b; };
          std::cout << "람다 합: " << add_lambda(5, 7) << std::endl;
      
          return 0;
      }
    



  • 도움이 되셨으면 하단의 ❤️ 공감 버튼 부탁 드립니다. 감사합니다! 😄

728x90
반응형

+ Recent posts