19.2 Template non-type parameters

주홍영·2022년 3월 22일
0

Learncpp.com

목록 보기
185/199

https://www.learncpp.com/cpp-tutorial/template-non-type-parameters/

이전 수업에서 우리는 template type parameter를 이용하여 type independant한 function과 class를 만든 것에 대해서 배웠다

하지만 template type parameter만이 유일한 사용처가 아니다
template class와 function은 non-type parameter라고 알려진 것도 만들 수 있다

Non-type parameters

A non-type parameter can be any of the following types:

  • An integral type
  • An enumeration type
  • A pointer or reference to a class object
  • A pointer or reference to a function
  • A pointer or reference to a class member function
  • std::nullptr_t
  • A floating point type (since C++20)

다음 예시에서 우리는 static array 클래스에서 이를 사용하는 것을 살펴본다

#include <iostream>

template <typename T, int size> // size is an integral non-type parameter
class StaticArray
{
private:
    // The non-type parameter controls the size of the array
    T m_array[size] {};

public:
    T* getArray();

    T& operator[](int index)
    {
        return m_array[index];
    }
};

// Showing how a function for a class with a non-type parameter is defined outside of the class
template <typename T, int size>
T* StaticArray<T, size>::getArray()
{
    return m_array;
}

int main()
{
    // declare an integer array with room for 12 integers
    StaticArray<int, 12> intArray;

    // Fill it up in order, then print it backwards
    for (int count { 0 }; count < 12; ++count)
        intArray[count] = count;

    for (int count { 11 }; count >= 0; --count)
        std::cout << intArray[count] << ' ';
    std::cout << '\n';

    // declare a double buffer with room for 4 doubles
    StaticArray<double, 4> doubleArray;

    for (int count { 0 }; count < 4; ++count)
        doubleArray[count] = 4.4 + 0.1 * count;

    for (int count { 0 }; count < 4; ++count)
        std::cout << doubleArray[count] << ' ';

    return 0;
}

template의 parameter에 int size라는 parameter가 존재한다
main 함수에서 int, 12 를 argument로 보내주고 있다
이런식으로 non-type parameter를 사용할 수 있다

만약 우리가 non-constexpr value로 non-type parameter를 설정하면 오류가 발생한다

template <int size>
class Foo
{
};

int main()
{
    int x{ 4 }; // x is non-constexpr
    Foo<x> f; // error: the template non-type argument must be constexpr

    return 0;
}

x의 value가 4이기는 하나 x는 non-constexpr이므로 error가 발생한다

profile
청룡동거주민

0개의 댓글