Static constant constexpr vs function

Is there a difference between declaring a floating point constant as a static constexpr variable and a function, as in the example below, or is it just a style question?

 class MY_PI { public: static constexpr float MY_PI_VAR = 3.14f; static constexpr float MY_PI_FUN() { return 3.14f; } } 
+50
c ++ c ++ 11 templates constexpr
Apr 29 '13 at 20:36
source share
1 answer

constexpr functions

Functions have the advantage that they do not have free variables (prior to C ++ 14): they can be easily planned without any class template. This means that you can have pi with precision depending on the template argument:

 template<typename T> constexpr T pi(); template<> constexpr float pi() { return 3.14f; } template<> constexpr double pi() { return 3.1415; } int main() { constexpr float a = pi<float>(); constexpr double b = pi<double>(); } 

However, if you decide to use a static member function instead of a free function, it will not be shorter or easier to write than a static member variable.

constexpr variables

The main advantage of using a variable is that ... good. You want a permanent, right? He clarifies the intention and may be one of the most important points here.

You can still have equivalent behavior with the class, but then you will have to use it like this if your class is a class containing different mathematical constants:

 constexpr float a = constants<float>::pi; 

Or, for example, if your class is only for representing pi :

 constexpr double = pi<double>::value; 

In the first case, you can use variables, because they will write shorter, and this will really show that you are using a constant and not trying to calculate something. If you have a class representing pi, you can, however, go with the free constexpr function instead of the whole class. It would be IMHO easier.

C ++ 14: constexpr variable templates

However, note that if you decide to use C ++ 14 instead of C ++ 11, you can write the following types of constexpr templates:

 template<typename T> constexpr T pi = T(3.1415); 

This will allow you to write your code as follows:

 constexpr float a = pi<float>; 

In C ++ 14, this may be the preferred way to do something. If you are using an older version of the standard, the first two paragraphs are still retained.

+51
Apr 30 '13 at 9:12
source share



All Articles