Replacing constants: when to use static constexpr and inline constexpr?

后端 未结 2 1189
无人及你
无人及你 2021-01-13 02:10

This question is a followup question to C++17: still using enums as constants?.

Legacy constants come in several forms, notably:

  • #define CONSTANT
2条回答
  •  一整个雨季
    2021-01-13 03:00

    In C++17, the proper way to replace those old idioms (e.g. #define) in headers in namespace scope is to use constexpr inline variables -- and not static (which is implied: they already have internal linkage).

    While typically you won't encounter ODR issues (because integer compile-time constants such as those you describe are rarely ODR-used and there is a provision for their typical usage within inline functions), it is best to mark them as inline now that we have the feature in the language and avoid all problems.

    See Should `const` and `constexpr` variables in headers be `inline` to prevent ODR violations? for the technical details about it.

提交回复
热议问题