【发布时间】:2018-09-20 22:03:13
【问题描述】:
我正在尝试用 constexpr 变量和 ifs 替换我用来控制条件编译的预处理器 #define 和 #if/#ifdef。
是否可以声明 constexpr 变量,以便它们重现 #defines,因为它们不分配运行时存储,并且获取 one 的地址会导致编译时错误?
编辑添加代码示例。
所以在标题中我想要类似的东西
namespace ExampleNamespace
{
enum class Platform : int {Darwin, Linux, Windows};
constexpr Platform BuildPlatform = Platform::Darwin; // Line A.
};
在我想要的代码中
if constexpr (Platform::Darwin == BuildPlatform) // Line B.
{
cout << "Platform is Darwin" << endl;
}
else
{
cout << "Platform is not Darwin" << endl;
};
const Platform *const PlatformAddress = &BuildPlatform; // Line C.
const Platform &BuildPlatform2 = BuildPlatform; // Line D.
然后目标是更改 A 行上 BuildPlatform 的定义,以便在编译时评估 B 行(并且 else 子句被丢弃/未编译)以及 C 和 D 行(以及任何做同样事情的东西,或依赖于 BuildPlatform 的运行时存储)会生成编译器错误。
这样的构造在 C++17 中是否可行?
【问题讨论】:
-
给出代码示例,原样,太宽泛了。
-
This 可能有帮助
-
地址比较容易被屏蔽(除非使用
std::addressof),但引用比较困难,也会导致ODR存在。您的变量是整数常量还是浮点值或究竟是什么? -
constexpr 不能帮助你有条件地存在变量,例如我不想有 int x;如果我在 Windows 上......而预处理器可以。
-
@Jarod42 添加了代码示例。
标签: c++ constants c++17 constexpr