为什么比较constexpr函数的两个参数不是静态断言的常量条件? [英] Why is comparing two parameters of a constexpr function not a constant condition for static assertion?

查看:816
本文介绍了为什么比较constexpr函数的两个参数不是静态断言的常量条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

constexpr uint32_t BitPositionToMask(int i,int Size){
static_assert(i < Size,"bit position out of range");
return 1 << i;
}

这会生成:

error: non-constant condition for static assertion

GCC 4.6.2我没有得到什么,还是这是GCC错误?

on GCC 4.6.2 Am I not getting something or is this a GCC bug?

更新:
谢谢Andy书呆子守护天使。因为我有编译时的值,我只是把它作为一个模板,它的工作原理。

Update: thank you Andy for being my nerd guardian angel again. Since I have the values at compile time anway I just made it a template and it works as intended.

template<int i,int Size>
constexpr uint32_t BitPositionToMask(){
    static_assert(i < Size,"bit position out of range");
    return 1 << i;
}


推荐答案

A constexpr 函数也可以使用在运行时评估的参数来调用(在这种情况下,它只是像任何常规函数一样执行)。例如,请参阅此 实例

A constexpr function can also be invoked with arguments evaluated at run-time (in that case, it just gets executed just like any regular function). See, for instance, this live example.

另一方面,A static_assert()严格要求其条件为可在编译时求值的常量表达式。

A static_assert(), on the other hand, strictly requires its condition to be a constant expression that can be evaluated at compile time.

这篇关于为什么比较constexpr函数的两个参数不是静态断言的常量条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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