728x90

explicit 키워드는 알고 있다시피 명시적으로 생성자를 호출하겠다는 의미이다.

조건부 explicit 생성자 키워드는 template를 사용할 때 편하게 이용할 수 있을 것 같다.

 

strcut A
{
    template<typename T>
    explicit(!std::is_same<T, bool>::value) A(T t)
    {
        cout << typeid(t).name() << endl;
    }
}

void TestA(A a)
{
}

int main()
{
    A a(true);
    TestA(a);     // 기본적으로 성공
    TestA(true);  // 조건이 맞기 때문에 성공
    TestA(10);    // 조건이 틀리므로 실패
    
    return 0;
}
728x90

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

C++20 - Template Parameter for Lambda  (0) 2023.12.28
C++20 - NonType Template Parameter  (0) 2023.12.28
C++20 - constinit  (2) 2023.12.27
C++20 - consteval  (1) 2023.12.27
C++20 - 지정된 초기화 (Designated Initialization)  (1) 2023.12.17

+ Recent posts