Constexpr decltype

走远了吗. 提交于 2019-12-05 10:55:12

constexpr expressions must be defined. Yours is not defined, so in that case int(constexpr_declval<int>()) is not constexpr.

Which means maybe_noexcept(int(constexpr_declval<int>())) is not a constexpr, so is not noexcept.

And the compiler properly returns false.

You also cannot invoke UB in a constexpr.

I cannot think of a way to make a constexpr reference to arbitrary data. I was thinking a constexpr buffer of aligned storage reinterpreted as a reference to the data type, but that is UB in many contexts, hence not-constexpr.

In general, this isn't possible. Imagine you had a class whose state determines if the method call is constexpr:

struct bob {
  int alice;
  constexpr bob(int a=0):alice(a) {}
  constexpr int get() const {
    if (alice > 0) throw std::string("nope");
    return alice;
  }
};

now, is bob::get constexpr or not? It is if you have a constexpr bob constructed with a non-positive alice, and ... it isn't if not.

You cannot say "pretend this value is constexpr and tell me if some expression is constexpr". Even if you could, it wouldn't solve the problem in general, because the state of a constexpr parameter can change if an expression is constexpr or not!

Even more fun, bob().get() is constexpr, while bob(1).get() is not. So your first attempt (default construct the type) even gave the wrong answer: you can test, then do the action, and the action will fail.

The object is effectively a parameter to the method, and without the state of al parameters, you cannot determine if a function is constexpr.

The way to determine if an expression is constexpr is to run it in a constexpr context and see if it works.

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