静态constexpr变量与函数 [英] static constexpr variable vs function
问题描述
将浮点常量声明为 static constexpr
变量和一个函数之间有区别,如下例所示,还是只是一个风格问题?
Is there a difference between declaring floating point constant as a static constexpr
variable and a function as in example below, or is it just a matter of style?
class MY_PI
{
public:
static constexpr float MY_PI_VAR = 3.14f;
static constexpr float MY_PI_FUN() { return 3.14f; }
}
推荐答案
constexpr
函数
函数有一个优点,自由变量没有(直到C ++ 14):它们可以很容易模板没有一些类样板。这意味着您可以根据模板参数精确地获得 pi
:
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>();
}
但是,如果你决定使用 static
成员函数而不是自由函数,它不会比 static
成员变量更短或更容易写。
However, if you decide to use a static
member function instead of a free function, it won't be shorter nor easir to write than a static
member variable.
使用变量的主要优点是...好。你想要一个常数,对吧?
The main advantage of using a variable is that... well. You want a constant, right? It clarifies the intent and that may be one of the most important points here.
constexpr float a = constants<float>::pi;
或者这样,如果你的类只是代表 pi
:
Or like this if your class is only meant to represent pi
:
constexpr double = pi<double>::value;
在第一种情况下,您可能更喜欢使用变量,因为它会更短,真的表明你正在使用一个常数,而不是试图计算的东西。如果你只有一个类代表pi,你可以使用一个自由的 constexpr
函数,而不是一个整体类。这将使IMHO更简单。
In the first case, you may prefer to use variables since it will be shorter to write and that will really show that you are using a constant and not trying to compute something. If you just have a class representing pi, you could however go with a free constexpr
function instead of a whole class. It would IMHO be simpler.
但是,请注意,如果选择使用C ++ 14而不是C + +11,您将能够编写以下类型的 constexpr
变量模板:
However, note that if you choose to use C++14 instead of C++11, you will be able to write the following kind of constexpr
variable templates:
template<typename T>
constexpr T pi = T(3.1415);
这样就可以这样编写代码:
That will allow you to write your code like this:
constexpr float a = pi<float>;
在C ++ 14中,这可能是首选的做事方式。如果您使用的是旧版本的标准,则前两个段落仍然有效。
In C++14, this may be the preferred way to do things. If you are using an older version of the standard, the first two paragraphs still hold.
这篇关于静态constexpr变量与函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!