c++c++17variadic-functions

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

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