patterncppCritical
Should I declare a constant instead of writing a constexpr function?
Viewed 0 times
constantfunctionshouldconstexprdeclareinsteadwriting
Problem
It seems to me that having a "function that always returns 5" is breaking or diluting the meaning of "calling a function". There must be a reason, or a need for this capability or it wouldn't be in C++11. Why is it there?
It seems to me that if I wrote a function that return a literal value, and I came up to a code-review, someone would tell me, I should then, declare a constant value instead of writing return 5.
// preprocessor.
#define MEANING_OF_LIFE 42
// constants:
const int MeaningOfLife = 42;
// constexpr-function:
constexpr int MeaningOfLife () { return 42; }It seems to me that if I wrote a function that return a literal value, and I came up to a code-review, someone would tell me, I should then, declare a constant value instead of writing return 5.
Solution
Suppose it does something a little more complicated.
Now you have something that can be evaluated down to a constant while maintaining good readability and allowing slightly more complex processing than just setting a constant to a number.
It basically provides a good aid to maintainability as it becomes more obvious what you are doing. Take
Its a pretty simple choice there but it does mean that if you call
Another good example would be a
Lots of good info here:
http://en.cppreference.com/w/cpp/language/constexpr
constexpr int MeaningOfLife ( int a, int b ) { return a * b; }
const int meaningOfLife = MeaningOfLife( 6, 7 );Now you have something that can be evaluated down to a constant while maintaining good readability and allowing slightly more complex processing than just setting a constant to a number.
It basically provides a good aid to maintainability as it becomes more obvious what you are doing. Take
max( a, b ) for example:template constexpr Type max( Type a, Type b ) { return a < b ? b : a; }Its a pretty simple choice there but it does mean that if you call
max with constant values it is explicitly calculated at compile time and not at runtime.Another good example would be a
DegreesToRadians function. Everyone finds degrees easier to read than radians. While you may know that 180 degrees is 3.14159265 (Pi) in radians it is much clearer written as follows:const float oneeighty = DegreesToRadians( 180.0f );Lots of good info here:
http://en.cppreference.com/w/cpp/language/constexpr
Code Snippets
constexpr int MeaningOfLife ( int a, int b ) { return a * b; }
const int meaningOfLife = MeaningOfLife( 6, 7 );template< typename Type > constexpr Type max( Type a, Type b ) { return a < b ? b : a; }const float oneeighty = DegreesToRadians( 180.0f );Context
Stack Overflow Q#4748083, score: 360
Revisions (0)
No revisions yet.