有没有办法通过'greater/lesser than'而不是"="来定义'int'?

Is there a way to define an 'int' by 'greater/lesser than' instead of '='?

本文关键字:int 定义 lesser greater 有没有 than      更新时间:2023-10-16

我在某个网站上玩了一个挑战,我遇到了这个问题。我有一个无法识别的整数...只有我知道它大于 x 或\和小于 y 等等......有没有办法基于 SO 定义变量?...我的意思是大于\小于整数..

有些人注意到not_null会有所帮助,但我无法理解如何......

这里有一些愚蠢的例子:

int some_unknown_number > 8;
if [some_unknown_number<=1] 
    {cout << "wrong" << endl;}

所以我希望代码能够认识到some_unknown_number不能小于 1,因为它已经大于 8。

ps:我不想要确切的答案...只要告诉我去哪里看,如果你明白我的意思....

你可以构建一个类,表示为

struct bounded
{
    std::optional<int> m_lower;
    std::optional<int> m_higher;
};

它对实例的下限和上限进行建模。如果两者都存在并设置为相同的值,则这显然模拟了一个普通int

然后,您根据此模型构建<运算符&c。

确实是一个有趣的问题。您可以定义您的类型。例如:

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;
  }
};

如果需要,您可以添加更多运算符来定义必要的语义,并像以下方式使用它:

// Int<19, 1> wrongInt; <--- compile time error.
Int<1, 3> myInt;
if (myInt > 0)
  printf("Greater than 0n");
if (myInt < 5)
  printf("Less than 5n");