有没有办法通过'greater/lesser than'而不是"="来定义'int'?
Is there a way to define an 'int' by 'greater/lesser than' instead of '='?
我在某个网站上玩了一个挑战,我遇到了这个问题。我有一个无法识别的整数...只有我知道它大于 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");
相关文章:
- 为什么"weak.lock()"返回"nullptr" "auto weak=std::make_shared<int>(42);"的定义?
- 在标准中,模板参数的语法在哪里定义,例如,'std::function<int(char)>'?
- 当我尝试定义这个向量时<pair<int , pair<int, int> > > vp(n)
- 定义 uint= "unsigned int" 没有像我在 Visual Studio 中使用 nvcc 时预期的那样应用
- C++ std::vector<int> 体系结构的未定义符号 x86_64:
- 我可以使用常量定义数组的长度,那么为什么 int d[b] 不起作用呢?
- 如何定义int[][26]类型的变量
- 从 int 显式转换为用户定义的类 c++
- 对'cv::VideoCapture::VideoCapture(int)的未定义引用
- 是否打印指向已定义 int 的成员指针
- 编译Qt项目给出了对运算符delete(void*,unsigned int)的未定义引用
- 从emxArray_uint8_T检测到错误:.text+0xc1):未定义对"emxInit_uint8_T1(emxArray_uint8_T**, int)"的引用?
- 对 'i2c_smbus_read_word_data(int, 无符号字符)的未定义引用
- 如何从输入中定义的"external" int 定义结构中的数组大小
- 在我的项目中包括eigen将标准INT定义为eigen :: denseIndex-如何使用正常INT
- 数据类型是否"int"定义为类?
- 为什么 sqrt() 在 int 变量上工作正常,如果它不是为 int 定义的
- 将默认int定义为unsigned int
- 为[z][y][x]int定义数组int[x][y][z]有什么好处?
- 用Const int定义数组