How does one use concepts in if constexpr
?
Given the example below, what would one give to if constexpr
to return 1 in case T
meets the requirements of integral
and else 0?
template<typename T> concept integral = std::is_integral_v<T>; struct X{}; template<typename T> constexpr auto a () { if constexpr (/* T is integral */) { return 1; } else { return 0; } } int main () { return a<X>(); }
The easiest way to check whether a function (e.g., foo ) is constexpr is to assign its return value to a constexpr as below: constexpr auto i = foo(); if the returned value is not constexpr compilation will fail.
Short answer: static_assert(false) should never appear in a constexpr if expression, regardless of whether it's in a template function or whether it's in the discarded branch.
A constexpr function is a function that can be invoked within a constant expression. A constexpr function must satisfy the following conditions: It is not virtual. Its return type is a literal type. Each of its parameters must be of a literal type.
Concepts are named boolean predicates on template parameters, evaluated at compile time.
In a constexpr if
statement, the value of the condition must be a contextually converted constant expression of type bool
.
So in this case, usage is simple:
if constexpr ( integral<T> )
It is sufficient to do:
if constexpr ( integral<T> )
since integral<T>
is already testable as bool
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With