Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing implicit cast of numerical types in constructor in C++

I have a constructor of the form:

MyClass(int a, int b, int c);

and it gets called with code like this:

MyClass my_object(4.0, 3.14, 0.002);

I would like to prevent this automatic conversion from double to int, or at least get warnings at compile time.

It seems that the "explicit" keyword does not work in these case, right?

like image 778
Hugo Avatar asked Feb 19 '10 08:02

Hugo


2 Answers

What's your compiler? Under gcc, you can use -Wconversion to warn you about these types of conversions.

like image 58
Martin B Avatar answered Oct 25 '22 02:10

Martin B


Declare a private constructor like this:

private:
template <class P1, class P2, class P3>
MyClass(P1,P2,P3);

That will cause a compile time error for any construction using 3 parameters that aren't all int, and it's portable.

like image 31
JoeG Avatar answered Oct 25 '22 01:10

JoeG