반응형

C++17 : 더욱 강력하고 효율적인 Modern C++

  • C++17C++11C++14에서 도입된 기능들을 기반으로 안정성과 성능을 개선하는 한편, 새로운 기능을 추가하여 개발자들이 더 효율적으로 코드를 작성할 수 있도록 돕는 표준입니다.
  • 특히, 코드의 가독성을 높이고, 실행 속도를 최적화하며, 기존의 불편했던 부분을 개선하는 데 초점을 맞추었습니다.

  • C++17에서 새롭게 도입된 주요 기능을 정리하면 다음과 같습니다.


1. 구조화된 바인딩 (Structured Bindings)

  • std::tuple, std::pair, struct 등의 값을 여러 변수에 한 번에 할당할 수 있음.

  • cpp

      #include <tuple>
      #include <iostream>
      
      std::tuple<int, double, char> getData() {
          return {42, 3.14, 'A'};
      }
      
      int main() {
          auto [x, y, z] = getData();
          std::cout << x << ", " << y << ", " << z << '\n';
      }
    


2. 조건문 초기화 (if/switch with Init Statement)

  • if 또는 switch문 내부에서 변수를 선언하고 초기화 가능.

  • cpp

      #include <iostream>
      
      int main() {
          if (int x = 10; x > 5) {
              std::cout << "x is greater than 5\n";
          }
      }
    


3. 선택적 값 (std::optional)

  • 값이 존재할 수도 있고 없을 수도 있는 경우를 표현하는 타입.

  • cpp

      #include <optional>
      #include <iostream>
      
      std::optional<int> getValue(bool giveValue) {
          if (giveValue) 
     		return 42;
     		
          return std::nullopt;
      }
      
      int main() {
          auto value = getValue(true);
          if (value) {
              std::cout << "Value: " << *value << '\n';
          }
      }
    


4. 대체 가능 타입 (std::variant)

  • 여러 타입 중 하나를 저장할 수 있는 union과 유사하지만 확장된 기능을 제공.

  • cpp

      #include <variant>
      #include <iostream>
      
      int main() {
          std::variant<int, double, std::string> var;
     	 
          var = 42;
          std::cout << std::get<int>(var) << '\n';
      
          var = "Hello";
          std::cout << std::get<std::string>(var) << '\n';
      }
    


5. 임의 타입 (std::any)

  • 어떤 타입이든 저장할 수 있으며, 타입 정보를 런타임에 확인 가능.

  • cpp

      #include <any>
      #include <iostream>
      
      int main() {
          std::any a = 42;
          std::cout << std::any_cast<int>(a) << '\n';
      
          a = std::string("Hello");
          std::cout << std::any_cast<std::string>(a) << '\n';
      }
    


6. 더 효율적인 문자열 처리 (std::string_view)

  • std::string보다 가벼운 읽기 전용 문자열 뷰 제공.

  • cpp

      #include <string_view>
      #include <iostream>
      
      void print(std::string_view sv) {
          std::cout << sv << '\n';
      }
      
      int main() {
          std::string s = "Hello, World!";
          print(s);
          print("Temporary String");
      }
    


7. 컴파일 타임 분기 (constexpr if)

  • if 문을 컴파일 타임에 평가하여 불필요한 코드 제거 가능.

  • cpp

      #include <iostream>
      
      template <typename T>
      void check(T value) {
          if constexpr (std::is_integral_v<T>) {
              std::cout << "Integral type\n";
          } else {
              std::cout << "Non-integral type\n";
          }
      }
      
      int main() {
          check(42);
          check(3.14);
      }
    


8. 병렬 알고리즘 (std::execution)

  • std::sort, std::for_each 등 알고리즘을 병렬 실행 가능.

  • cpp

      #include <algorithm>
      #include <execution>
      #include <vector>
      #include <iostream>
      
      int main() {
         std::vector<int> v = {5, 3, 8, 1, 9};
         std::sort(std::execution::par, v.begin(), v.end());
      
         for (int n : v) 
     		std::cout << n << ' ';
      }
    


9. 파일 시스템 라이브러리 (std::filesystem)

  • 파일 및 디렉토리 조작을 위한 기능 제공.

  • cpp

      #include <filesystem>
      #include <iostream>
      
      int main() {
          std::filesystem::path p = "/home/user";
          std::cout << "Path: " << p << '\n';
          std::cout << "Exists? " << std::filesystem::exists(p) << '\n';
      }
    


10. 일반화된 호출 (std::invoke)

  • 함수, 함수 객체, 멤버 함수 등을 동일한 방식으로 호출 가능.

  • cpp

      #include <functional>
      #include <iostream>
      
      void hello() {
          std::cout << "Hello!\n";
      }
      
      int main() {
          std::invoke(hello);
      }
    


11. 가변 템플릿 간소화 (Fold Expression)

  • ...을 이용해 여러 개의 인자를 축약하는 기능.

  • cpp

      #include <iostream>
      
      template <typename... Args>
      void print(Args... args) {
          ((std::cout << args << " "), ...);
      }
      
      int main() {
          print(1, 2, "Hello", 3.14);
      }
    


12. Aggregate Initialization 개선

  • struct의 초기화 방식이 향상됨.

  • cpp

      struct Data {
          int x;
          double y;
      };
      
      int main() {
          Data d{10, 3.14};  // C++17에서 허용됨
      }
    


  • C++17은 단순히 새로운 기능을 추가하는 것뿐만 아니라, 기존 코드의 가독성과 유지보수성을 높이는 데 초점을 맞춘 업데이트였습니다.
  • 특히, std::optional, std::variant, std::string_view 등의 기능은 기존의 복잡한 구현을 단순화하는 데 큰 도움이 됩니다.
  • 또한, if constexpr을 활용하면 불필요한 코드 생성을 방지하여 보다 최적화된 프로그램을 만들 수 있습니다.

  • 이처럼 C++17은 개발자들이 더 효율적이고 간결한 코드를 작성할 수 있도록 돕는 중요한 업데이트였습니다. 😊
728x90
반응형

+ Recent posts