How to define a constexpr variable

I want to use a simple compile-time constant, for example:

double foo(double x) { return x + kConstDouble; } 

Now I see at least the following ways to define a constant

 namespace { static constexpr double kConstDouble = 5.0; } namespace { constexpr double kConstDouble = 5.0; } static constexpr double kConstDouble = 5.0; constexpr double kConstDouble = 5.0; 

Which is the right way? Is there any difference when kConstDouble is defined in the header or source file?

+5
source share
1 answer

Using a static or anonymous namespace will cause the variable to have an internal relationship; it will be displayed only within one translation unit. Therefore, if you use one of these in the .cpp file, you cannot use this variable anywhere else. This will be done if the constant is a detail of the implementation of this code unit. If you want to put it on other translation units, you need to put it in the header file. A typical way to do this would be to declare it static (or put it in an anonymous namespace), as this is a trivial and constant variable. Another approach would be to declare it extern in the header and define it in .cpp to get a truly global variable (as opposed to the top one where in fact each tu has its own copy).

Between a static and anonymous namespace; it’s good that you don’t need it in the first place. They both do the same as AFAIK. But I think it is currently more idiomatic to use anonymous namespaces in cpp files, as they can be used to provide functions, classes, etc. Intercom. On the other hand, when you want to use it to create a globally accessible variable, static is more often used; I never use anonymous namespaces in header files, as I find this to be misleading.

0
source

Source: https://habr.com/ru/post/1235270/


All Articles