Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>(); } 
like image 788
nnolte Avatar asked Feb 07 '19 12:02

nnolte


People also ask

How do I know if a function is constexpr?

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.

Which is false about constexpr?

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.

What is a constexpr function?

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.


2 Answers

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> ) 
like image 198
P.W Avatar answered Oct 14 '22 18:10

P.W


It is sufficient to do:

if constexpr ( integral<T> ) 

since integral<T> is already testable as bool

like image 45
nnolte Avatar answered Oct 14 '22 16:10

nnolte