g++ doesn#39;t compile constexpr function with assert in it(g++ 不会编译带有 assert 的 constexpr 函数)
问题描述
<块引用>
错误: constexpr 函数体 'constexpr T getClamped(const T&, const T&, const T&) [with T = long unsigned int]' 不是返回语句
使用 g++ 4.8.1.clang++ 3.4 不会抱怨.
谁在这里?有什么方法可以让 g++ 在不使用宏的情况下编译代码?
解决方案
GCC 是对的.但是,有一个相对简单的解决方法:
我们两次滥用逗号操作符.
第一次是因为我们想要一个 assert,当 true 时,可以从 constexpr 函数调用.第二个,所以我们可以将两个函数链接成一个 constexpr 函数.
作为附带的好处,如果 constexpr_assert 表达式在编译时无法验证为 true,则 getClamped 函数不是 <代码>constexpr
.
assert_helper
的存在是因为assert
的内容是NDEBUG
为真时定义的实现,所以我们不能把它嵌入到表达式中(它可以是语句,而不是表达式).它还保证失败的 constexpr_assert
失败是 constexpr
即使 assert
是 constexpr
(比如,当 NDEBUG
为假).
所有这一切的一个缺点是您的断言不是在发生问题的行触发,而是在更深的 2 个调用处触发.
error: body of constexpr function 'constexpr T getClamped(const T&, const T&, const T&) [with T = long unsigned int]' not a return-statement
Using g++ 4.8.1
. clang++ 3.4
doesn't complain.
Who is right here? Any way I can make g++
compile the code without using macros?
GCC is right. However, there is a relatively simple workaround:
where we abuse the comma operator, twice.
The first time because we want to have an assert
that, when true
, can be called from a constexpr
function. The second, so we can chain two functions into a single constexpr
function.
As a side benefit, if the constexpr_assert
expression cannot be verified to be true
at compile time, then the getClamped
function is not constexpr
.
The assert_helper
exists because the contents of assert
are implementation defined when NDEBUG
is true, so we cannot embed it into an expression (it could be a statement, not an expression). It also guarantees that a failed constexpr_assert
fails to be constexpr
even if assert
is constexpr
(say, when NDEBUG
is false).
A downside to all of this is that your assert fires not at the line where the problem occurs, but 2 calls deeper.
这篇关于g++ 不会编译带有 assert 的 constexpr 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!