Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

expand parameter pack with boolean operation

I tried to do function that checks if the argument matches specific values.

I think know how to do it with recursion or std::initializer_list, but I want to do it with fold. Here is non working code:

template<typename T, T ...ts>
constexpr bool is_in(T value){
    return (ts == value) || ... || (false);
}

int main(){
    if constexpr(is_in<int, 1, 2, 3>(1))
        return 10;

}

Also I would like to get rid of specifying the type if possible (e.g. the <int>)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Want solution in C++17, but C++20 would be interesting to see as well.

>Solution :

Fold expressions must be enclosed in (...): return ((ts == value) || ... || (false));.

Also you can drop || false, it’s implicit for || folds.

Also I would like to get rid of specifying the type if possible (e.g. the <int>)

You can do this by replacing <typename T, T ...ts> with e.g. <auto ...ts, typename T>.

But if I was you, I’d pass all alternatives as function parameters (to allow them to be changed at runtime).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading