如果表达式为constexpr,则为static_assert [英] static_assert if expressions is constexpr

查看:77
本文介绍了如果表达式为constexpr,则为static_assert的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个班级模板

template <class T>
class X {
  // here I'll use T::value (among other things)
};

T :: value 通常是constexpr静态变量,但并非总是如此. T :: value 必须为正值,所以我想让人们尽可能地在编译过程中知道它.

T::value will often be a constexpr static variable, but not always. T::value has to be positive value, so I want to let people know it during compilation, when possible.

如果 T :: value 始终是constexpr,我将像

那样添加 static_assert

If T::value was always constexpr, I'd add static_assert like

static_assert(T::value > 0, "need positive number");

仅在 T :: value 为constexpr的情况下才可以添加此static_assert吗?

Is it possible to add this static_assert only for cases when T::value is constexpr?

推荐答案

我们可以编写一个带有两个重载的 is_valid 模板函数(用一个更好的名字命名):

We can write an is_valid template function (come up with a better name) with two overloads:

template <typename T, int N = T::value>
constexpr bool is_valid(int) {
    return N > 0;
}

template <typename T>
constexpr bool is_valid(...) {
    return true;
}

仅当 T :: value 是一个常量表达式时,第一个重载才有效,否则将被SFINAEd清除.无论如何,第二个重载都是有效的,因此我们使用伪 int 参数消除了重载的歧义.

The first overload will only be valid if T::value is a constant expression, otherwise it will be SFINAEd out. The second overload is valid no matter what, so we disambiguate the overload with a dummy int parameter.

现在我们像这样测试它:

Now we test it like so:

static_assert(is_valid<T>(0), "need positive number");

实时演示

这篇关于如果表达式为constexpr,则为static_assert的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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