Software Workshop

상수값을 대입하여 변수를 만들 때, 다양한 타입으로 처리할 수 있도록 해주는 기능이 C++14에 도입되었다. 이것을 "variable template"이라고 부르며 상수 파라미터의 사용을 단순화하는 효과를 낼 수 있다.

아래 예제에서 템플릿으로 정의된 변수 pi가 variable template에 해당하며, 상수값의 타입이 float인지, double인지, long double인지 아직 결정되지 않은 상태이다. 상수값의 타입이 정해지면 그에 따라서 변수의 타입도 정해지도록 사용하는 기법이라고 할 수 있다.

상수값의 타입을 지정하는 방법으로 (float) 1.10000000000000000002l처럼 캐스팅하는 방법이 있고, 또는 1.10000000000000000002f로 postfix를 이용하여 float 타입의 리터럴임을 알리는 방법이 있다.

#include <iostream>
#include <iomanip>

using namespace std;

template<typename T> constexpr T pi = T(3.141592653589732385);
template<typename T> T area_of_circle_with_radius(T r) {
    return pi<T> * r * r;
}

int main(void)
{
    cout << setprecision(25);
    cout << area_of_circle_with_radius(1) << endl;
    cout << area_of_circle_with_radius((float) 1.10000000000000000002l) << endl;
    cout << area_of_circle_with_radius((double) 1.10000000000000000002l) << endl;
    cout << area_of_circle_with_radius((long double) 1.10000000000000000002L) << endl;
    cout << area_of_circle_with_radius(1.10000000000000000002f) << endl;
    cout << area_of_circle_with_radius(1.10000000000000000002) << endl;
    cout << area_of_circle_with_radius(1.10000000000000000002l) << endl;

    return 0;
}

실행 결과를 보면 파라미터로 사용된 상수값의 타입에 따라 함수 템플릿에서 타입이 결정되어 정밀도가 제각각 다른 결과가 반환됨을 확인할 수 있다.

3
3.8013274669647216796875
3.801327110843576662091436
3.801327110843576053854018
3.8013274669647216796875
3.801327110843576662091436
3.801327110843576053854018