반응형
struct A
{
A() = default;
A(int n)
{
cout << n << endl;
}
};
void TestA(A a)
{
}
struct B
{
template<typename T>
explicit B(T t)
{
}
};
void TestB(B b)
{
}
void main()
{
A a;
TestA(a);
TestA(10);
B b1(22);
TestB(b1);
//TestB(123); error
//TestB("hi"); error
}
TestA(a); 처럼 말고도 TestA(10); 이런 식으로도 호출이 가능하다.
왜냐하면 생성자 중에서 정수를 받아주는 생성자가 있기 때문에 가능하다.
이런 경우를 막기 위해 explicit 키워드를 붙여주면 더 이상 TestA(10); 처럼 호출이 불가능 하다.
explicit : 원하지 않는 형변환이 일어나지 않도록 제한하는 키워드
struct C
{
template<typename T>
explicit(!std::is_same<T, bool>::value) C(T t)
{
cout << typeid(t).name() << endl;
}
};
void TestC(C c)
{
}
void main()
{
C c1 = true;
TestC(c1);
TestC(true);
//TestC(10); error
}
조건부 Explicit
-bool에 의한 간접 변환 (Implicit Conversion)은 허용
-그 외에는 Explicit
반응형
'C++' 카테고리의 다른 글
C++ 20 : Template Parameter for Lambda (0) | 2024.05.19 |
---|---|
C++ 20 : Non-Type Template Parameter (0) | 2024.05.19 |
C++ 20 : consteval/constinit (0) | 2024.05.17 |
C++ 20 : Designated Initialization(지정 초기화) (0) | 2024.05.17 |
C++ 20 : Three-Way Comparison (< = > 연산자) (0) | 2024.05.16 |