jeudi 25 décembre 2014

When to use explicit specifier for multi-argument constructors?

I have recently learned about the explicit specifier.


Suppose we have:



f( W, W, W );


Now if we do



f( 42, 3.14, "seven" );


The compiler will attempt the following implicit conversions:



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


If we have defined matching constructors for W, namely:



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


...it will succeed.


However, if we make the first one explicit:



explicit W(int);


... this disables the implicit conversion.


You would now have to write:



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


i.e. it is forcing you to explicitly state the conversion


Now on to the question:


It is possible to write:



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


This compiles!


But I can't see any corresponding scenario that might require this syntax.


Can anyone provide a minimal example?


Aucun commentaire:

Enregistrer un commentaire