Basic Programming/C++ 20

C++20 - NonType Template Parameter

Stayner 2023. 12. 28. 22:54
728x90

우리가 알고 있는 template를 선언할 때는 아래와 같다

template<typename T>

 

여기에서 typename 대신에 NonType으로 다음과 같이 사용이 가능했다.

int, enum, pointer, reference, nullptr_t 등은 기존에도 사용이 가능했다.

template<int T>

 

이번 C++20에서는 몇가지를 더 사용할 수 있게 되었다.

- Floating-point
- Literal Type (types of constexpr variables)
- String Literal

 

Floating-point를 사용하는 예제

template<double d>
auto GetDouble()
{
   return d;
}

int main()
{
    auto d1 = GetDouble<5.5>();

    return 0;
}

 

Literal Type (types of constexpr variables)을 사용하는 예제

struct ClassType
{
    constexpr ClassType(int) {}
}

template<ClassType t>
auto GetClassType()
{
    return t;
}

int main()
{
    auto t1 = GetClassType<1>();

    return 0;
}

 

String Literal

template<int N>
class StringLiteral
{
public:
    constexpr StringLiteral(char const (&str)[N])
    {
        std::copy(str, str+N, _data);
    }
    
    char _data[N];
}

template<StringLiteral str>
class ClassTemplate {};

template<StringLiteral str>
void FunctionTemplate()
{
    cout << str data << endl;
}

int main()
{
    ClassTemplate<"Hello World"> cls1;
    FunctionTemplate<"Hello">();

    return 0;
}
728x90