【发布时间】:2017-12-09 07:48:45
【问题描述】:
来自那个问题: How to build a custom macro that behaves differently when used as constexpr (like assert)?
我想知道为什么可以调用非 constexpr 函数,如果它是有条件的。
void bla( )
{
std::cout << "bla called!" << std::endl;
}
constexpr bool check(bool condition)
{
//bla(); // can not directly be called -> not constexpr!
condition ? void (0) : bla(); // compiles and runs even if condition is true or false!
// if condition is const, it did not compile because it
// directly force execution of non constexpr function
true ? void(0): bla(); // also that compiles!, ok, directly evaluated
//true ? bla(): void(0); // that did not compile;)
//false ? void(0): bla(); // that did not compile;)
false ? bla(): void(0); // compiles, ok, directly evaluated
return 0;
}
int main()
{
check( false );
check( true );
}
有人能解释一下标准中给出了哪些规则吗? 正如 W.F. 所评论的那样:如果在 constexpr 术语中使用结果,例如 模板参数,如果条件导致评估则失败 非 constexpr 函数。
这使得assert 在编译时直接抱怨如果结果是
在 constexpr 术语中使用。
【问题讨论】:
-
这就是 constexpr 的工作原理。
-
衬衫电路禁用
bla()... /跨度> -
@W.F.:由于来自断言宏,它扩展为我在此处编写的内容,因此存在某种差异。如果它不是 constexpr,则将调用 assert 函数。所以这里面还是有一定的玄机的。所以如果更改为
in_range( 7, 1, 5 )我会得到一个编译错误,对!但是 assert 函数会起作用。但为什么呢? -
你能举个例子吗?据我了解,您使用非 constexpr 参数调用 in_range 。这仍然没有放宽函数上给出的 constexpr 条件。
-
@W.F.:我再次简化了我的示例,并且两次都运行了。没有短路,如果 bla 是条件表达式的一部分,则执行 bla。所以我想知道为什么不允许直接调用!