본문 바로가기

Programming/C++14

[C++14] Variable Template (변수 템플릿)

C++14에 새로 생긴 Language Feature로, 어떤 변수에 대해서 템플릿화 할 수 있다.

 

// 변수 템플릿
template <typename T>
constexpr T PI = static_cast<T>(3.1415926535897932);

// 변수 템플릿 특수화
template <>
constexpr const char* PI<const char*> = "PI";

int main() {
    cout << PI<int>         << endl;
    cout << PI<float>       << endl;
    cout << PI<double>      << endl;
    cout << PI<const char*> << endl;

    return 0;
}

 

 

+ 정적 멤버 변수도 사용 가능하다.

 

class MathConstants {
    public:
        // 정적 멤버 변수 템플릿
        template <typename T>
        static constexpr T PI = static_cast<T>(3.1415926535897932);
};

// 정적 멤버 변수 템플릿 특수화
template <>
constexpr const char* MathConstants::PI<const char*> = "PI";

int main() {
    cout << MathConstants::PI<int>         << endl;
    cout << MathConstants::PI<float>       << endl;
    cout << MathConstants::PI<double>      << endl;
    cout << MathConstants::PI<const char*> << endl;

    return 0;
}

 

 

- 실행 결과

 

<MinGW g++ 13.2.0, c++17 옵션 사용>

 

 


Variable Template 기능은 C++20 std library에 추가된 <numbers> 파일에 실제 사용되었다.

 

<numbers> 파일 내부 코드 중 일부


Reference

'Programming > C++14' 카테고리의 다른 글

[C++14] Digit Separator (자리 구분자)  (0) 2024.04.08
[C++14] Binary Literal (이진 상수)  (1) 2024.03.29