Ad

How To Use Concepts In If Statement

- 1 answer

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
}
Ad

Answer

Concept instantiations implicitely convert to 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 {
    // ...
}
Ad
source: stackoverflow.com
Ad