Monday, July 24, 2017

C++11: constexpr: function declaration

By marking things constexpr, you can use them in initialization that is performed at compile-time. Here is an example:
#include <iostream>
constexpr int orBits(int bit2, int bit1, int bit0)
{
  return int(4 * int(bit2) | int(2 * bit1)+int(bit0));
}
int orBits2(int bit2, int bit1, int bit0)
{
  return int(4 * int(bit2) | int(2 * bit1)+int(bit0));
}
int main()
{
  int x = 7;
  switch (x)
  {
   case orBits(1, 1, 1):
    std::cout << 7 << std::endl;
    break;
  }

  switch (x)
  {
// case orBits2(1, 1, 1): // Error: expression did not evaluate to a 
                          //          constant.
    std::cout << 7 << std::endl;
    break;
  }

  return 0;
}
// Output: 7
Reference: https://isocpp.org/wiki/faq/cpp11-language#cpp11-constexpr

No comments:

Post a Comment