본문 바로가기
-----ETC-----/C++ 고급 프로그래밍과 응용 프로젝트 시리즈

[C++ 고급 프로그래밍과 응용 프로젝트 시리즈] Day 4: C++20의 개념과 모듈

by cogito21_cpp 2024. 8. 1.
반응형

Concepts (개념)

Concepts는 템플릿 인자의 요구사항을 명확히 정의하는 새로운 기능입니다. Concepts를 사용하면 코드의 가독성과 유지보수성을 크게 향상시킬 수 있습니다.

 

Concepts의 기본 사용법

Concepts는 템플릿 인자에 대해 특정 조건을 명시할 수 있습니다. 이를 통해 템플릿 함수나 클래스가 특정 타입이나 속성에 대해서만 작동하도록 할 수 있습니다.

 

기본 사용법 예제

#include <iostream>
#include <concepts>

// 정수 타입에 대해서만 작동하는 Concept 정의
template <typename T>
concept Integral = std::is_integral_v<T>;

// Integral 타입에 대해서만 작동하는 함수
template <Integral T>
void func(T value) {
    std::cout << "Integral type function with value: " << value << std::endl;
}

int main() {
    func(10);        // Integral type function with value: 10
    // func(3.14);   // 컴파일 오류
    // func("Hello"); // 컴파일 오류

    return 0;
}

 

위의 코드에서 Integral이라는 Concept을 정의하고, 이를 템플릿 함수 func의 제약 조건으로 사용합니다. func 함수는 정수 타입에 대해서만 작동합니다.

 

여러 Concepts 사용

여러 Concepts를 결합하여 사용할 수도 있습니다.

 

여러 Concepts 사용 예제

#include <iostream>
#include <concepts>

// 정수 타입에 대해서만 작동하는 Concept 정의
template <typename T>
concept Integral = std::is_integral_v<T>;

// 부동 소수점 타입에 대해서만 작동하는 Concept 정의
template <typename T>
concept FloatingPoint = std::is_floating_point_v<T>;

// Integral 또는 FloatingPoint 타입에 대해서만 작동하는 함수
template <typename T>
requires Integral<T> || FloatingPoint<T>
void func(T value) {
    std::cout << "Number type function with value: " << value << std::endl;
}

int main() {
    func(10);        // Number type function with value: 10
    func(3.14);      // Number type function with value: 3.14
    // func("Hello"); // 컴파일 오류

    return 0;
}

 

이 예제에서 func 함수는 정수 타입 또는 부동 소수점 타입에 대해서만 작동합니다.


모듈 (Modules)

모듈은 C++20에서 도입된 새로운 기능으로, 코드의 분할과 재사용을 보다 쉽고 효율적으로 할 수 있게 합니다. 모듈은 컴파일 시간 단축과 코드 숨김을 통해 빌드 시스템을 개선합니다.

 

모듈의 기본 사용법

모듈은 export module 키워드를 사용하여 정의합니다.

 

모듈 정의

먼저, 모듈을 정의하는 파일을 생성합니다 (mymodule.ixx).

// mymodule.ixx
export module mymodule;

export int add(int a, int b) {
    return a + b;
}

 

모듈 사용

모듈을 사용하는 파일을 생성합니다 (main.cpp).

// main.cpp
import mymodule;
#include <iostream>

int main() {
    std::cout << "3 + 4 = " << add(3, 4) << std::endl;
    return 0;
}

 

컴파일

모듈을 사용하려면, 컴파일러와 빌드 시스템이 모듈을 지원해야 합니다. 모듈을 사용하여 컴파일하려면 다음 명령어를 사용합니다.

g++ -std=c++20 -fmodules-ts mymodule.ixx -c -o mymodule.o
g++ -std=c++20 main.cpp mymodule.o -o main
./main

 

이 명령어는 mymodule.ixx 파일을 컴파일하여 모듈 객체 파일을 생성하고, main.cpp 파일을 컴파일하여 실행 파일을 생성합니다.


실습 문제

문제 1: Concepts를 사용하여 특정 타입에 대해 작동하는 템플릿 함수 작성

Concepts를 사용하여 정수 타입에 대해서만 작동하는 템플릿 함수를 작성하세요.

 

해설:

#include <iostream>
#include <concepts>

// 정수 타입에 대해서만 작동하는 Concept 정의
template <typename T>
concept Integral = std::is_integral_v<T>;

// Integral 타입에 대해서만 작동하는 함수
template <Integral T>
void check(T value) {
    std::cout << "Integral type with value: " << value << std::endl;
}

int main() {
    check(10);        // Integral type with value: 10
    // check(3.14);   // 컴파일 오류
    // check("Hello"); // 컴파일 오류

    return 0;
}

 

문제 2: 모듈을 사용하여 두 개의 함수 정의 및 사용

모듈을 사용하여 두 개의 함수를 정의하고, 이를 사용하는 프로그램을 작성하세요. 함수는 addsubtract 함수를 정의하세요.

 

해설:

먼저, 모듈을 정의하는 파일을 생성합니다 (mymodule.ixx).

// mymodule.ixx
export module mymodule;

export int add(int a, int b) {
    return a + b;
}

export int subtract(int a, int b) {
    return a - b;
}

 

모듈을 사용하는 파일을 생성합니다 (main.cpp).

// main.cpp
import mymodule;
#include <iostream>

int main() {
    std::cout << "3 + 4 = " << add(3, 4) << std::endl;
    std::cout << "7 - 2 = " << subtract(7, 2) << std::endl;
    return 0;
}

 

컴파일

g++ -std=c++20 -fmodules-ts mymodule.ixx -c -o mymodule.o
g++ -std=c++20 main.cpp mymodule.o -o main
./main

 

이제 4일차의 학습을 마쳤습니다. Concepts와 모듈에 대해 상세히 학습하고 실습 문제를 풀어보았습니다.

 

질문이나 피드백이 있으면 언제든지 댓글로 남겨 주세요. 내일은 "범위 기반 for 루프와 초기화 리스트"에 대해 다루겠습니다.

반응형