赋值中有条件的
conditional in value assignment
在c++中,我想在赋值时使用条件词,例如:
int i = true && 5 || 3;
例如,使用Lua,您可以编写以下内容:
i = true and 5 or 3
我不确定这是否可能
这是我尝试过的东西:
#include "stdafx.h"
#include <iostream>
void main()
{
int test = (true && 5) || 1;
int test2 = (false && 6) || 2;
std::cout << "Test: " << test << std::endl << "Test2: " << test2 << std::endl;
for(;;);
}
C++不是Lua。
在Lua中,true and 5
的表达导致5
。这就是Lua处理布尔表达式的简单方式。
这不是C++处理布尔表达式的方式。在C++中,布尔表达式会产生布尔值。即true
或false
。
如果你想根据一个条件在两个值之间进行选择,我们有一个运算符:
int i = true ? 5 : 3;
如果条件为true,则获得:
之前的值。如果它为false,则获得:
之后的值。
我怀疑您正在寻找int test = true ? 5 : 1;
您需要的是一个条件表达式:
int i = true ? 2 : 5;
在这种情况下,i
将是2。
如果我们真的想,从c++11开始(这给了我们and
和or
关键字作为&&
和||
的同义词),我们几乎可以强大地武装c++编译器使其符合要求,并让它编译以下内容:
int x = when_true(b) and 5 or 6;
为了做到这一点,我们需要提供一些脚手架:
#include <iostream>
struct maybe_int {
bool cond;
int x;
operator int() const { return x; }
};
int operator || (const maybe_int& l, int r) {
if (l.cond) return l.x;
return r;
}
struct when_true {
when_true(bool condition)
: _cond(condition)
{}
auto operator&&(int x) const {
return maybe_int { _cond, x };
}
bool _cond;
};
int main()
{
using namespace std;
auto b = false;
int x = when_true(b) and 5 or 6;
cout << x << endl;
return 0;
}
我的建议是你不要在工作中尝试这种事情。
相关文章:
- 有没有办法在C++的赋值中将"char**"转换为"double"?
- 对于单个数据 WORD 的 memcpy 和赋值语句有什么区别?
- 在C++中,当表达式涉及对象时,将表达式赋值到对象中时,是否有定义的操作顺序?
- 有条件地将初始值设定项列表中的shared_ptr设为 null
- 有条件的操作员从其参数的副本中返回值
- 是否有必要重载具有另一个类 B 的数据成员的类 A 的赋值运算符和复制构造函数?
- 对条件表达式结果的赋值(其中第二个和第三个操作数是相同类型和值类别的变量)是否仍然存在?
- 就地赋值和再次使用变量名称的赋值有什么区别?
- 有没有办法通过从另一个文件中读取值来为宏赋值
- 我们不能在未赋值的上下文中命名非静态成员函数是有原因的吗
- 有可能将多个整数赋值为一吗
- 为赋值编写伪代码,并希望仔细检查它是否有意义
- 默认赋值运算符有权访问基类的私有成员
- 初始化对象后,用隐式转换而不是赋值运算符调用构造函数有什么意义
- 赋值运算符和条件语句
- 赋值或条件绑定更强
- 赋值运算符和复制构造函数有什么区别?
- 有没有一种方法可以使用std::array与文字或初始值设定项列表进行比较,就像使用赋值一样
- 赋值中有条件的
- 是否有没有赋值的增量运算符