Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use concepts in if statement

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
}
like image 389
Tiko7454 Avatar asked Oct 14 '25 03:10

Tiko7454


1 Answers

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 {
    // ...
}
like image 52
Salvage Avatar answered Oct 18 '25 07:10

Salvage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!