问题描述
我的库中有几个简短的constexpr
函数,它们执行一些简单的计算.我在运行时上下文和编译时上下文中都使用它们.
I have several brief constexpr
functions in my libraries that perform some simple calculations. I use them both in run-time and compile-time contexts.
我想在这些函数的主体中执行一些断言,但是assert(...)
在constexpr
函数中无效,并且static_assert(...)
不能用于检查函数参数.
I would like to perform some assertions in the body of these functions, however assert(...)
is not valid in a constexpr
function and static_assert(...)
can not be used to check function parameters.
示例:
constexpr int getClamped(int mValue, int mMin, int mMax) noexcept
{
assert(mMin <= mMax); // does not compile!
return mValue < mMin ? mMin : (mValue > mMax ? mMax : mValue);
}
有没有一种方法可以检查该函数是在运行时常量还是在编译时常量中执行,并且仅当assert
在运行时执行时才执行? >
Is there a way to check whether the function is being executed in a run-time or compile-time constant and execute the assert
only if it's being executed at run-time?
constexpr int getClamped(int mValue, int mMin, int mMax) noexcept
{
assert_if_runtime(mMin <= mMax);
return mValue < mMin ? mMin : (mValue > mMax ? mMax : mValue);
}
推荐答案
我相信,一旦g ++实现了 N3652,放松对constexpr函数的约束.当前,此状态页面表示尚未实现.
I believe that assert
will work for you once g++ implements N3652, Relaxing constraints on constexpr functions. Currently, this status page indicates that this has not yet been implemented.
assert
在Apple附带的当前clang编译器上使用-std=c++1y
可以正常工作(在constexpr函数中).
assert
does work (in constexpr functions) on the current clang compiler shipped by Apple, with -std=c++1y
.
这时,我在标准中看不到任何可以保证assert
在constexpr函数中工作的东西,而且这种保证将是对该标准的一个受欢迎的补充(至少对我而言).
At this time, I see nothing in the standard that assures one that assert
will work in constexpr functions, and such an assurance would be a welcome addition to the standard (at least by me).
更新
Richard Smith提请我注意DanielKrügler提交的 LWG 2234 试图建立我上面提到的保证.
Richard Smith drew my attention to LWG 2234 submitted by Daniel Krügler which is attempting to create the assurance I refer to above.
这篇关于如何在C ++中为constexpr函数参数使用static_assert?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!