C++ 使用constexpr替换条件编译的#define和#ifdef

C++ 使用constexpr替换条件编译的#define和#ifdef,c++,constants,c++17,constexpr,C++,Constants,C++17,Constexpr,我试图用constexpr变量和ifs替换用于控制条件编译的预处理器#define和#if/#ifdef 是否可以声明constexpr变量,以便它们复制#定义,因为它们不分配运行时存储,并且获取一个变量的地址会导致编译时错误 编辑以添加代码示例。 因此,在标题中,我希望有类似的内容 namespace ExampleNamespace { enum class Platform : int {Darwin, Linux, Windows}; constexpr Platform Bu

我试图用constexpr变量和ifs替换用于控制条件编译的预处理器#define和#if/#ifdef

是否可以声明constexpr变量,以便它们复制#定义,因为它们不分配运行时存储,并且获取一个变量的地址会导致编译时错误

编辑以添加代码示例。 因此,在标题中,我希望有类似的内容

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.
if constexpr(Platform::Darwin==BuildPlatform)//行B。
{

cout部分可能:

if constexpr (Platform::Darwin == BuildPlatform) {        // Line B.
    std::cout << "Platform is Darwin" << std::endl;
} else {
    std::cout << "Platform is not Darwin" << std::endl;
}
如果constexpr(平台::达尔文==BuildPlatform){//行B。

对于标志和整数,枚举值起作用

对于浮点值,没有constexpr方法可以保证不使用ODR。ODR的使用往往会导致为常量创建存储


您可以使用返回浮点值的constexpr函数,但该函数很容易占用存储空间。

也许您可以使用此函数

enum class Platform { Darwin, Linux, Windows };

#ifdef __darwin__
constexpr Platform  BuildPlatform = Platform::Darwin;
#elif __linux__
constexpr Platform  BuildPlatform = Platform::Linux;
#elif __WIN32
constexpr Platform  BuildPlatform = Platform::Windows;
#endif

// your code then uses it like this

if constexpr (BuildPlatform == Platform::Darwin) 
{         
}
else if constexpr (BuildPlatform == Platform::Linux)
{
}
else if constexpr (BuildPlatform == Platform::Windows)
{   
}

按原样给出代码示例,它太宽了。可能helpAddress相对容易被阻止(除非使用
std::addressof
),但引用是困难的,它也会导致ODR的存在。您的变量是整型常量还是浮点值,或者是什么?constexpr不能帮助您有条件地存在变量,例如,我不想有int x;如果我在Windows上,而预处理器可以。@Jarod42添加了代码示例。不,这是不可能的。see[另一个答案][
enum class Platform { Darwin, Linux, Windows };

#ifdef __darwin__
constexpr Platform  BuildPlatform = Platform::Darwin;
#elif __linux__
constexpr Platform  BuildPlatform = Platform::Linux;
#elif __WIN32
constexpr Platform  BuildPlatform = Platform::Windows;
#endif

// your code then uses it like this

if constexpr (BuildPlatform == Platform::Darwin) 
{         
}
else if constexpr (BuildPlatform == Platform::Linux)
{
}
else if constexpr (BuildPlatform == Platform::Windows)
{   
}