When to use an explicit specifier for constructors with multiple arguments?

I recently found out about the explicit qualifier.

Let's pretend that:

 f( W, W, W ); 

Now if we do

 f( 42, 3.14, "seven" ); 

The compiler will attempt to perform the following implicit conversions:

 f( W(42), W(3.14), W("seven") ); 

If we defined matching constructors for W, namely:

 W(int); W(double); W(std::string); 

... it will be successful.

However, if we make the first explicit:

 explicit W(int); 

... this disables implicit conversion.

Now you need to write:

 f( W(42), 3.14, "seven" ); 

i.e. it makes you explicitly specify the conversion

Now to the question:

You can write:

 explicit W(int,int); // 2 arguments! 

It compiles!

But I do not see any relevant script that this syntax might require.

Can someone provide a minimal example?

+5
source share
1 answer

If your constructor is explicit and the class does not provide an implicit constructor that takes initializer_list<T> , then you cannot copy-list-initialize an instance.

 W w = {1,2}; // compiles without explicit, but not with 

Simple live example

 #include <iostream> class A { public: explicit A(int, int) {} }; class B { public: B(int, int) {} }; int main() { B b = {1,2}; A a = {1,2}; } 

Quotes from the standard:

8.5 / 16

- If the initializer is the (not beveled) bracket-init-list, the object or link is initialized with a list (8.5.4).

8.5.4 / 3

An initialization list of an object or link of type T is defined as follows: ...

Otherwise, if T is a class type, constructors are considered. Applicable constructors are listed and selected best through overload resolution (13.3, 13.3.1.7). If a narrowing conversion (see below) is required to convert any of the arguments, the program is poorly formed.

+10
source

Source: https://habr.com/ru/post/1209876/


All Articles