Reputation: 29
I was playing around in a challenge on some website, and I met this problem. i have an unidentified integer ... only I know that it is greater that x or\and lesser that y and so on ... is there a way to define a variable based on so? ... I mean as being greater\lesser than integer ..
some have noted that not_null would help but I couldn't understand how ..
here is some silly example :
int some_unknown_number > 8;
if [some_unknown_number<=1]
{cout << "wrong" << endl;}
so I expect the code to recognize that some_unknown_number can't be lesser than 1 since it's already larger than 8....
ps: I don't want the exact answer ... just tell me where to look if you know what I mean ....
Upvotes: 1
Views: 946
Reputation: 21240
Interesting question, indeed. You can define your type. For example:
template<int Min, int Max>
struct Int
{
static_assert(Max > Min, "Max should be greater than Min");
bool operator<(int val) const
{
return val > Max;
}
bool operator>(int val) const
{
return Min > val;
}
};
You can add more operators, if needed, to define necessary semantics, and use it like:
// Int<19, 1> wrongInt; <--- compile time error.
Int<1, 3> myInt;
if (myInt > 0)
printf("Greater than 0\n");
if (myInt < 5)
printf("Less than 5\n");
Upvotes: 2
Reputation: 234785
You could build a class representing this as
struct bounded
{
std::optional<int> m_lower;
std::optional<int> m_higher;
};
which models the lower and upper bound of an instance. If both are present and set to the same value, this clearly models a plain int
.
You then build your <
operator &c. in accordance with this model.
Upvotes: 4