Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

c++ - Why is comparing two parameters of a constexpr function not a constant condition for static assertion?

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

this generates:

error: non-constant condition for static assertion

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

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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(), on the other hand, strictly requires its condition to be a constant expression that can be evaluated at compile time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...