39

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>();
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nnolte
  • 1,628
  • 11
  • 25

2 Answers2

31

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> )
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
P.W
  • 26,289
  • 6
  • 39
  • 76
22

It is sufficient to do:

if constexpr ( integral<T> )

since integral<T> is already testable as bool

nnolte
  • 1,628
  • 11
  • 25