On Delphi I can write:
type TExample = -1..High(Word)-1; Is it possible to do something similar in C ++?
If so, how?
// псевдокод typedef int[-1..65534] TExample; Well, if you still need a bike, then catch it - I think you will add the functionality you need:
#include<iostream> class MyShort { public: static const int MAX_EL {65534}; static const int MIN_EL {-1}; private: int number_; public: MyShort () { }; MyShort (int num) { if (num <= MAX_EL && num >= MIN_EL) { number_ = num; } else { number_ = -1; } }; ~MyShort() { }; MyShort &operator=(MyShort &a) { number_ = a.number_; return *this; }; MyShort &operator=(int num) { if (num <= MAX_EL && num >= MIN_EL) { number_ = num; } else { number_ =-1; } return *this; }; }; int main(int argc, char *argv[]) { MyShort alfa {}; alfa = 5; alfa = -1; return 0; } But again, I repeat: it is devoid of any meaning !!! Since there is no separation in memory, this is a matter of simple interpretation: so -1 and 65535 are absolutely identical bit sequences in memory (for a 2-byte type). For example:
unsigned short alfa = -1; unsigned short beta = 65535; if (alfa == beta) { std::cout << "Comp" << std::endl; } It will display messages (in this case, if you change only one of the type numbers, then when comparing, they will be reduced to int and the numbers will no longer be the same, since these will not be 2 byte numbers).
You can also try this:
__extension__ typedef enum __attribute__ ((__packed__)) { ES = 500, EE } mytype_t; printf( "size: %zu\n", sizeof(mytype_t)); With this scheme, the compiler uses the smallest type that will contain all the values. The size should be 2, logically, and will be incremented by 1 for each increase + = 256.
There is also the option -fshort-enums for GCC, clang, this leads the enum type to a state of type signed short ..
This is certainly not a ready-made solution, but a direction to think about how this can be organized with the help of compiler extensions.
A counter question to the author: what do you want to achieve?
If you generate run-time checks for out of range, then you are mistaken with the language. C ++ on the contrary gets rid of everything that you can get rid of in runtime. Check is needed - create your own class and overload the assignment operator.
If you want to push this range in two bytes and use -1 as a signaling state, then you can easily use the value 65535 as a signaling state, sticking it into a constant. If it should be less than 0, then again, the class and operator overloading.
Delphi has another specific application. This is, firstly, the heir to the educational language Pascal, which required rigor, not speed. Secondly, it is a language for desktop business applications, where, theoretically, reliability is more important than speed.
Source: https://ru.stackoverflow.com/questions/852679/
All Articles
throw try catch- Andrej Levkovitchclassyourself :) - in which you will know exactly what it does. - Harry