On 14 Apr 2017 20:38:29 GMT,
r...@zedat.fu-berlin.de (Stefan Ram)
wrote:
> Some other languages (like Pascal or COBOL) provide types
> for ranges and enumerations, and I wonder to which extend
> one can create such types in C++.
>
> For example,
>
>struct example { range<2'000'000'000,2'000'000'010> i; };
>
> . The implementation should emit an error message (a
> compile-time error message if possible) when one tries to
>
>instance.i = 0;
>
> , and, if possible,
>
>sizeof instance.i
>
> should be just 1, because one byte is enough to store
> one out of 10 values.
While only a rough outline, a template with conversion operators, like
the following, should provide a start. This does require the actual
storage type to be explicitly specified, I'm not sure how you'd
generate that automatically from the range.
#include <stdexcept>
template<typename T, long MN, long MX>
class rangetype
{
T v;
void setv(long a)
{
if (a < MN || a > MX)
throw std::out_of_range("blah");
v=a-MN;
}
public:
rangetype& operator=(long a) {setv(a); return *this;}
operator long() {return v+MN;}
};
int main()
{
int a;
char b;
rangetype<char, 100, 200> q;
rangetype<int, 100, 2000> r;
q = 3;
q = 3.14;
a = q;
b = q;
r = q;
}