C++11 - static_assert within constexpr function?

时光总嘲笑我的痴心妄想 提交于 2019-11-26 04:46:42

问题


How would one properly do a static_assert within a constexpr function? For example:

constexpr int do_something(int x)
{
  static_assert(x > 0, \"x must be > 0\");
  return x + 5;
}

This is not valid C++11 code, because a constexpr function must only contain a return statement. I don\'t think that the standard has an exception to this, although, the GCC 4.7 does not let me compile this code.


回答1:


This is not valid C++11 code, because a constexpr function must only contain a return statement.

This is incorrect. static_assert in a constexpr function are fine. What is not fine is using function parameters in constant expressions, like you do it.

You could throw if x <= 0. Calling the function in a context that requires a constant expression will then fail to compile

constexpr int do_something(int x) {
  return x > 0 ? (x + 5) : (throw std::logic_error("x must be > 0"));
}



回答2:


This works and is valid C++11 code, because template arguments are compile time only:

template <int x>
constexpr int do_something() {
    static_assert(x > 0, "x must be > 0");
    return x + 5;
}

I faced with the same problems as you did with constant expressions in C++. There's few clear documentation about constexprs at the moment. And note that there's some known bugs with it in gcc's issue tracker, but your problem seems not to be a bug.

Note that if you declare constexpr functions inside classes, you are not able to use them inside the class. This also seems to be not a bug.

Edit: This is allowed according to the standard: 7.1.3 states

... or a compound-statement that contains only

  • null statements,
  • static_assert-declarations
  • typedef declarations and alias-declarations that do not
    define classes or enumerations,
  • using-declarations,
  • using-directives,
  • and exactly one return statement


来源:https://stackoverflow.com/questions/8626055/c11-static-assert-within-constexpr-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!