赋值中有条件的

conditional in value assignment

本文关键字:有条件 赋值      更新时间:2023-10-16

在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++中,布尔表达式会产生布尔值。即truefalse

如果你想根据一个条件在两个值之间进行选择,我们有一个运算符:

int i = true ? 5 : 3;

如果条件为true,则获得:之前的值。如果它为false,则获得:之后的值。

我怀疑您正在寻找int test = true ? 5 : 1;

您需要的是一个条件表达式:

  int i = true ? 2 : 5;

在这种情况下,i将是2。

如果我们真的想,从c++11开始(这给了我们andor关键字作为&&||的同义词),我们几乎可以强大地武装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;
}

我的建议是你不要在工作中尝试这种事情。