0
Why explicit constructor does not fail for variant
Hi Please refer code below: I have explicit constructor and hence expecting v3 object to throw compile time error. https://sololearn.com/compiler-playground/c7eBraGbSvOS/?ref=app
1 Antwort
0
When you use direct initialization syntax like variant<test,int> v3(3);, the compiler tries to match the provided argument directly with the constructors of the variant's types. In this case, it sees the integer 3 and finds that it can directly use the int constructor without needing an implicit conversion.
If you were to use copy initialization syntax (e.g., variant<test,int> v3 = 3;), the compiler would need to perform an implicit conversion to match the argument with the constructors of the variant's types. In this scenario, the explicit constructor of test would prevent the implicit conversion, and the code would fail to compile.
Since 3 is an int, the compiler can directly match it with the int constructor in the variant without considering the test constructor, even though the test constructor is marked as explicit.
To prevent implicit conversions, you can use a different initialization approach or rearrange the types in the variant. For example:
variant<test,int> v3 = 3;
OR
variant<test,int> v3(test(3));