Roger Lipscombe
Roger Lipscombe

Reputation: 91885

Forcing single-argument constructors to be explicit in C++?

By default, in C++, a single-argument constructor can be used as an implicit conversion operator. This can be suppressed by marking the constructor as explicit.

I'd prefer to make "explicit" be the default, so that the compiler cannot silently use these constructors for conversion.

Is there a way to do this in standard C++? Failing that, is there a pragma (or similar) that'll work in Microsoft C++ to do this? What about g++ (we don't use it, but it might be useful information)?

Upvotes: 28

Views: 25474

Answers (6)

bk1e
bk1e

Reputation: 24328

If there was a pragma or command line option that made constructors explicit by default, how would you declare one that is not explicit? There would have to be another compiler-specific token or pragma to make it possible to declare an implicit conversion constructor.

Upvotes: 2

MP24
MP24

Reputation: 3200

There is no such option in the compilers, as far as I am aware. But there is a Lint warning for such cases (see http://www.gimpel.com/lintinfo.htm).

Upvotes: 1

MSalters
MSalters

Reputation: 179981

It could be rather nasty for any header you have. Like <vector>, or any of the Boost headers. It would also cause quite a few false bugreports. So, no, I don't expect a compiler to add such a #pragma.

Upvotes: 1

Matt Price
Matt Price

Reputation: 45425

Nope, you have to do it all by hand. It's a pain, but you certainly should get in the habit of making single argument constructors explicit. I can't imagine the pain you would have if you did find a solution and then had to port the code to another platform. You should usually shy away from compiler extensions like this because it will make the code less portable.

Upvotes: 24

luke
luke

Reputation: 37463

There's no such option available in standard c++, and I don't believe there is in Visual Studio either.

Upvotes: 0

Scott Langham
Scott Langham

Reputation: 60381

I think the answer is no!

Sorry, its not a very constructive answer. I hope somebody else might know more!

Upvotes: 0

Related Questions