4

I have a concept which checks whether a type is iterable or not

template<typename T> concept Iterable = requires(T t) { t.begin(); }; 

I cannot use it in a template due to problems with overloading, so I'd like to do something similar to the following:

template<typename T> void universal_function(T x) { if (x is Iterable) // something which works with iterables else if (x is Printable) // another thing else // third thing } 
1
  • @Incomputable I think you're switching up if consteval with if constexpr, consteval doesn't seem relevant here. Commented Feb 20, 2022 at 14:41

2 Answers 2

10

Concept instantiations are boolean values, so they can be used in if statements. You will need to use if constexpr to achieve the desired behavior, as it will allow for branches containing code that would be invalid in a different branch:

if constexpr (Iterable<T>) { // ... } else if constexpr (Printable<T>) { // ... } else { // ... } 
Sign up to request clarification or add additional context in comments.

3 Comments

I think, what OP was missing here was not the if constexpr feature per se, but the fact that concepts can be used in boolean expressions directly. What constexpr provides is the ability to write code in one branch that would be invalid in another, which you can't do with a regular if.
@SU3 Very true! I've edited my answer to address this :)
They don't just implicitly convert to bool, they are bool.
2

You can directly write the requires clause inside the if to determine the validity of the expression, something like this

template<typename T> void universal_function(T x) { if constepxr (requires { x.begin(); }) { // something which works with iterables } else if constepxr (requires { std::cout << x; }) { // another thing } else { // third thing } } 

But it seems that only detecting whether x.begin() is well-formed is not enough for iterable types, the standard library already has a concept for this, namely std::ranges::range:

if constepxr (std::ranges::range<T>) { // something which works with iterables } 

1 Comment

Pretty cool feature that I didn't know about, but you're missing bodies for the first two ifs ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.