nnolte
nnolte

Reputation: 1780

How do I use concepts in if-constexpr?

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>();
}

Upvotes: 40

Views: 6875

Answers (2)

nnolte
nnolte

Reputation: 1780

It is sufficient to do:

if constexpr ( integral<T> )

since integral<T> is already testable as bool

Upvotes: 27

P.W
P.W

Reputation: 26800

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> )

Upvotes: 31

Related Questions