在我看来,拥有一个“总是返回5的函数”破坏或稀释了“调用函数”的意义。必须有一个原因,或者需要这个功能,否则它就不会出现在c++ 11中。为什么会在那里?

// preprocessor.
#define MEANING_OF_LIFE 42

// constants:
const int MeaningOfLife = 42;

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

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


当前回答

所有其他的答案都很棒,我只是想给一个很酷的例子,你可以用constexpr做一件很棒的事情。See-Phit (https://github.com/rep-movsd/see-phit/blob/master/seephit.h)是一个编译时HTML解析器和模板引擎。这意味着您可以放入HTML,然后取出能够操作的树。在编译时进行解析可以提供一些额外的性能。

从github页面的例子:

#include <iostream>
#include "seephit.h"
using namespace std;



int main()
{
  constexpr auto parser =
    R"*(
    <span >
    <p  color="red" height='10' >{{name}} is a {{profession}} in {{city}}</p  >
    </span>
    )*"_html;

  spt::tree spt_tree(parser);

  spt::template_dict dct;
  dct["name"] = "Mary";
  dct["profession"] = "doctor";
  dct["city"] = "London";

  spt_tree.root.render(cerr, dct);
  cerr << endl;

  dct["city"] = "New York";
  dct["name"] = "John";
  dct["profession"] = "janitor";

  spt_tree.root.render(cerr, dct);
  cerr << endl;
}

其他回答

例如std::numeric_limits<T>::max():不管出于什么原因,这是一个方法。Constexpr在这里很有用。

另一个例子:你想声明一个与另一个数组一样大的c数组(或std::array)。目前的做法是这样的:

int x[10];
int y[sizeof x / sizeof x[0]];

但如果能这样写不是更好吗:

int y[size_of(x)];

感谢constexpr,你可以:

template <typename T, size_t N>
constexpr size_t size_of(T (&)[N]) {
    return N;
}

何时使用constexpr:

只要有编译时间常数。

它在某些方面很有用

// constants:
const int MeaningOfLife = 42;

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

int some_arr[MeaningOfLife()];

将它与特质类或类似的类联系起来,它会变得非常有用。

所有其他的答案都很棒,我只是想给一个很酷的例子,你可以用constexpr做一件很棒的事情。See-Phit (https://github.com/rep-movsd/see-phit/blob/master/seephit.h)是一个编译时HTML解析器和模板引擎。这意味着您可以放入HTML,然后取出能够操作的树。在编译时进行解析可以提供一些额外的性能。

从github页面的例子:

#include <iostream>
#include "seephit.h"
using namespace std;



int main()
{
  constexpr auto parser =
    R"*(
    <span >
    <p  color="red" height='10' >{{name}} is a {{profession}} in {{city}}</p  >
    </span>
    )*"_html;

  spt::tree spt_tree(parser);

  spt::template_dict dct;
  dct["name"] = "Mary";
  dct["profession"] = "doctor";
  dct["city"] = "London";

  spt_tree.root.render(cerr, dct);
  cerr << endl;

  dct["city"] = "New York";
  dct["name"] = "John";
  dct["profession"] = "janitor";

  spt_tree.root.render(cerr, dct);
  cerr << endl;
}

刚刚开始将一个项目切换到c++11,遇到了一个非常好的constexpr情况,它清理了执行相同操作的替代方法。这里的关键点是,只有当函数声明为constexpr时,才能将其放入数组大小声明中。在许多情况下,我可以看到这在我所从事的代码领域非常有用。

constexpr size_t GetMaxIPV4StringLength()
{
    return ( sizeof( "255.255.255.255" ) );
}

void SomeIPFunction()
{
    char szIPAddress[ GetMaxIPV4StringLength() ];
    SomeIPGetFunction( szIPAddress );
}