By kawillzocken


2019-02-07 12:32:06 8 Comments

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

2 comments

@kawillzocken 2019-02-07 12:36:10

It is sufficient to do:

if constexpr ( integral<T> )

since integral<T> is already testable as bool

@Vittorio Romeo 2019-08-15 15:44:32

Is this still valid in the latest draft of the Standard? Or do we need requires integral<T> instead?

@P.W 2019-02-07 13:10:48

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

@Vittorio Romeo 2019-08-15 15:44:29

Is this still valid in the latest draft of the Standard? Or do we need requires integral<T> instead?

Related Questions

Sponsored Content

27 Answered Questions

[SOLVED] How do you set, clear, and toggle a single bit?

76 Answered Questions

[SOLVED] How do I iterate over the words of a string?

  • 2008-10-25 08:58:21
  • Ashwin Nanjappa
  • 2119444 View
  • 2852 Score
  • 76 Answer
  • Tags:   c++ string split

24 Answered Questions

[SOLVED] Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

7 Answered Questions

[SOLVED] constexpr overloading

1 Answered Questions

[SOLVED] Can a concept require a constexpr value or function?

  • 2018-05-16 07:25:35
  • jcarpenter2
  • 152 View
  • 1 Score
  • 1 Answer
  • Tags:   c++ c++-concepts

1 Answered Questions

[SOLVED] C++ concepts and std::cout

1 Answered Questions

[SOLVED] if constexpr and requires-expression for ad-hoc concepts checking

1 Answered Questions

[SOLVED] C++ TS Concepts and accessors

4 Answered Questions

[SOLVED] Why main can not be a constexpr?

1 Answered Questions

[SOLVED] Hypothetical, formerly-C++0x concepts questions

Sponsored Content