如何在 C++ 中将 static_assert 用于 constexpr 函数参数? [英] How to use static_assert for constexpr function arguments in C++?

查看:22
本文介绍了如何在 C++ 中将 static_assert 用于 constexpr 函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的库中有几个简短的 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);
}

推荐答案

assert 现在可以工作了,因为 g++ 已经实现了 N3652,放宽对 constexpr 函数的约束.这个状态页表明这已经在gcc5中实现了.

assert works now that g++ has implemented N3652, Relaxing constraints on constexpr functions. This status page indicates that this has been implemented in gcc5.

assert 也适用于 Apple 提供的当前 clang 编译器(在 constexpr 函数中),使用 -std=c++1y.

assert also works (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 提请我注意 Daniel 提交的 LWG 2234Krügler 试图建立我上面提到的保证.这已被纳入 C++17.

Richard Smith drew my attention to LWG 2234 submitted by Daniel Krügler which is attempting to create the assurance I refer to above. This has been incorporated into C++17.

这篇关于如何在 C++ 中将 static_assert 用于 constexpr 函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆