在编译时在头文件中计算常量

时间:2018-07-29 19:39:50

标签: c++ c++11

我有一个头文件,其中包含基于用户操作系统的功能,它使用:

#ifdef _WIN32 // Windows
...
#else // Linux/Unix code (I know it will be either Windows or Linux/Unix)
...
#endif

当前在运行时从main调用在其相应块中定义的函数并存储一个常量,但这使我想到:我可以在编译时在标头中计算此常量吗?

类似的东西:

#ifdef _WIN32 
// function here; call it foobar()
#define WINCONST foobar()
#else
// function here; call it xfoobar()
#define NIXCONST xfoobar()
#endif

但是,我不确定您可以在#define预处理程序指令中使用函数调用。我知道您可以使用#define ADD(x, y) (x + y)之类的方式使用它,仅此而已。

1 个答案:

答案 0 :(得分:3)

类似的东西:

constexpr uint32_t foo()
{
    // complex calculations...
    return 0;
}

uint32_t const SomeConstant = foo();

旁注:foo将被评估为编译时间常数,只要不传递任何非编译时间参数,因此上面的定义也将产生一个编译时间常数(等效于uint32_t SomeConstant = 7;)。但是,如果您从foo中删除constexpr限定符,则代码不会中断,除非您在需要编译时间常数的地方使用该常数(例如,数组定义)。这可能是不希望的,在后一种情况下,constexpr提供了更强的保证(即,只要foo(/*...*/)的编译时间不是恒定的,编译就会失败):

uint32_t constexpr SomeConstant = foo();
相关问题