Literal Class Type as Non-type Template Parameter

2022. 4. 2. 20:43C++

C++20 이전에는 템플릿 파라미터로 사용할 수 있는 non-type으로는 다음과 같은 것들이 있었다.

C++20 이후부터는 실수형 타입 및 클래스 타입도 템플릿 파라미터로 사용할 수 있게 되었다.

  • a floating-point type;
  • a literal class type with the following properties:
     - all base classes and non-static data members are public and non-mutable and
     - the types of all base classes and non-static data members are structural types or (possibly multi-dimensional) array thereof.

하지만, 보는 것과 같이 사용할 수 있는 클래스 타입에 제약이 있다.

- 리터럴 클래스 타입

- 모든 부모 클래스(base class)와 비정적(non-static) 멤버 변수들이 public 및 non-mutable.

(protected/private 멤버 함수는 가능하다.)

- 모든 부모 클래스와 비정적 멤버 변수들이 structural 타입이거나 (아마도 다차원의) 그것들의 배열.

(sturctural 타입은 위에 제시된 타입들을 의미한다.)

 

따라서 C++20 이후부터는 다음과 같은 코드가 가능하다.

template <std::array ARR>
void PrintLiteralArray()
{
    for (const auto& value : ARR)
    {
        cout << value << endl;
    }
}

int main()
{
    PrintLiteralArray<{ 1, 2, 3 }>();
    return 0;
}

템플릿 인자로 CTAD(Class Template Argument Deduction)에 의해 std::array<int, 3>{1, 2, 3} 또는 std::array{1, 2, 3}아닌 {1, 2, 3}을 바로 전달함으로써 CTAD를 사용하지 않았을 때 보다 훨씬 간결하게 표현하였다.

 

[참고]

- Literal Classes as Non-type Template Parameters in C++20

- https://en.cppreference.com/w/cpp/language/template_parameters