什么时候应该在C ++ 11中使用constexpr能力?

问题描述:

在我看来,有一个总是返回5的函数打破或稀释调用函数的含义。必须有一个原因,或者需要这个能力,否则它不会在C ++ 11中。为什么会有?

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?

// preprocessor.
#define MEANING_OF_LIFE 42

// constants:
const int MeaningOfLife = 42;

// constexpr-function:
constexpr int MeaningOfLife () { return 42; }

在我看来,如果我写了一个函数返回一个字面值,代码审查,有人会告诉我,我应该声明一个常量值,而不是写返回5。

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.

假设它做一些更复杂的事情。

Suppose it does something a little more complicated.

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.

它基本上提供了一个很好的辅助可维护性,因为它变得更加明显你在做什么。取 max(a,b)例如:

It basically provides a good aid to maintainability as it becomes more obvious what you are doing. Take max( a, b ) for example:

template< typename Type > 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.

另一个很好的例子是 DegreesToRadians 函数。每个人都发现比弧度更容易阅读。虽然你可能知道180度是以弧度,它更清楚地写如下:

Another good example would be a DegreesToRadians function. Everyone finds degrees easier to read than radians. While you may know that 180 degrees is in radians it is much clearer written as follows:

const float oneeighty = DegreesToRadians( 180.0f );

这里有很多好处:

http://www.informit.com/guides/content.aspx?g=cplusplus& seqNum = 315