伪造真 ↔ 假
Falsify true ↔ false
这道题没有实际用处!我问这个只是因为我很好奇!
在 C++ 中有一种方法可以通过在某处编写 #define true false
来将 true 伪造为 false,然后代码中的所有 true
都将被视为 false
。但是我正在寻找一种方法来同时将 true
伪造为 false
并将 false
伪造为 true
:
#define true false
#define false true
这不起作用,尝试“保存”原始 true
也不起作用:
#define temptrue true
#define true false
#define false temptrue
你知道怎么做吗?
这显然没有任何实际用途,也不是有效的 C++,但下面的方法可以解决问题:
static constexpr auto fake_true = false;
static constexpr auto fake_false = true;
#define true fake_true
#define false fake_false
简单地使用数字文字(例如 1 和 0)可能看起来更简单,但在类型很重要的情况下(例如重载解析)会导致不同的语义。
也许是这样的?
#define false static_cast<bool>(1)
#define true static_cast<bool>(0)
关于未定义的行为:
那些说未定义的可能指的是这个问题的答案:Is it legal to redefine a C++ keyword?
但是,如果您不使用标准 C++ 库,则引用的限制不适用(Bathsheba 和 Martin York 的荣誉)。
16.5.4.1 [constraints.overview]
Subclause 16.5.4 describes restrictions on C++ programs that use the facilities of the C++ standard library.
...
16.5.4.3.2 [macro.names] ...
A translation unit shall not #define
or #undef
names lexically identical to keywords, ...
C++ 2020 draft
使用 constexpr
变量而不是改变 true
和 false
的行为。
static constexpr bool TRUE = false;
static constexpr bool FALSE = true;
尝试 #define
C++ 关键字的行为未定义。不要这样做!
不是很漂亮,但是
static constexpr bool true_ = false;
static constexpr bool false_ = true;
可能是你能做的最好的了。
这道题没有实际用处!我问这个只是因为我很好奇!
在 C++ 中有一种方法可以通过在某处编写 #define true false
来将 true 伪造为 false,然后代码中的所有 true
都将被视为 false
。但是我正在寻找一种方法来同时将 true
伪造为 false
并将 false
伪造为 true
:
#define true false
#define false true
这不起作用,尝试“保存”原始 true
也不起作用:
#define temptrue true
#define true false
#define false temptrue
你知道怎么做吗?
这显然没有任何实际用途,也不是有效的 C++,但下面的方法可以解决问题:
static constexpr auto fake_true = false;
static constexpr auto fake_false = true;
#define true fake_true
#define false fake_false
简单地使用数字文字(例如 1 和 0)可能看起来更简单,但在类型很重要的情况下(例如重载解析)会导致不同的语义。
也许是这样的?
#define false static_cast<bool>(1)
#define true static_cast<bool>(0)
关于未定义的行为:
那些说未定义的可能指的是这个问题的答案:Is it legal to redefine a C++ keyword?
但是,如果您不使用标准 C++ 库,则引用的限制不适用(Bathsheba 和 Martin York 的荣誉)。
16.5.4.1 [constraints.overview]
Subclause 16.5.4 describes restrictions on C++ programs that use the facilities of the C++ standard library.
...
16.5.4.3.2 [macro.names] ...
A translation unit shall not#define
or#undef
names lexically identical to keywords, ...
C++ 2020 draft
使用 constexpr
变量而不是改变 true
和 false
的行为。
static constexpr bool TRUE = false;
static constexpr bool FALSE = true;
尝试 #define
C++ 关键字的行为未定义。不要这样做!
不是很漂亮,但是
static constexpr bool true_ = false;
static constexpr bool false_ = true;
可能是你能做的最好的了。