c++ - 使用constexpr代替#define和#ifdef进行条件编译

标签 c++ constants c++17 constexpr

我正在尝试用 constexpr 变量和 ifs 替换我用来控制条件编译的预处理器 #define 和 #if/#ifdef。

是否可以声明 constexpr 变量,使它们重现 #defines,因为它们不分配运行时存储,并且取一个地址会导致编译时错误?

编辑以添加代码示例。

所以在标题中我想有类似的东西

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 中可能吗?

最佳答案

部分可能:

if constexpr (Platform::Darwin == BuildPlatform) {        // Line B.
    std::cout << "Platform is Darwin" << std::endl;
} else {
    std::cout << "Platform is not Darwin" << std::endl;
}

但是作为template <typename T> void foo() {static_assert(false);}是病态的, 所有分支的代码都应该具有某种有效性。

#ifdef (DarwinPlatform) // constexpr cannot be used here, you have to 
                        //rely on MACRO here
# include <darwin.h>     // Some OS specific header
#endif

void foo()
{
    if constexpr (Platform::Darwin == BuildPlatform) {
        DarwinMethod(); // Won't compile on other platforms as
                        // the method doesn't exist.
        // you should make the block template with template dependent code
        // to allow code to compile.
        // as http://coliru.stacked-crooked.com/a/c695575e4dcdecee
    }
}

关于c++ - 使用constexpr代替#define和#ifdef进行条件编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52433953/

相关文章:

c++ - 在 libclang 访问者中将成员函数作为参数传递

c++ - 如何在没有 sysfs/library 的情况下控制 GPIO

c++ - 无法确定为什么代码在打印后停止 113383

c++ - 容器及其内容的 const 与非 const

c++ - 模板实例化解析错误

c++ - 如何在 C++ 中初始化返回元组的变量?

c++ - gcc - 如何在结构定义中组合 __attribute__((dllexport)) 和 [[nodiscard]]?

c++ - 使用枚举作为数组索引

c - const char* 应该在 C 中释放吗?

c# - 为什么不能将结构声明为 const?