Can I make a strong typed integer in C ++?

I need a strong typed integer in C ++ that compiles in Visual Studio 2010.

I need this type to act as an integer in some patterns. In particular, I must be able to:

StrongInt x0(1); //construct it. auto x1 = new StrongInt[100000]; //construct it without initialization auto x2 = new StrongInt[10](); //construct it with initialization 

I have seen things like:

 class StrongInt { int value; public: explicit StrongInt(int v) : value(v) {} operator int () const { return value; } }; 

or

 class StrongInt { int value; public: StrongInt() : value(0) {} //fails 'construct it without initialization //StrongInt() {} //fails 'construct it with initialization explicit StrongInt(int v) : value(v) {} operator int () const { return value; } }; 

Since these things are not PODs, they do not quite work.

+4
source share
2 answers

I just use an enumeration type when I want a strongly typed integer.

 enum StrongInt { _min = 0, _max = INT_MAX }; StrongInt x0 = StrongInt(1); int i = x0; 
+1
source
 StrongInt x0(1); 

Since these things are not PODs, they do not quite work.

These two things are incompatible: you cannot have constructor syntax and PODness. For POD you will need to use, for example. StrongInt x0 { 1 }; or StrongInt x0 = { 1 }; , or even StrongInt x0({ 1 }); (this is a very round initialization).

+1
source

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


All Articles