Search code examples
c++c++11c++17variadic-templatesvariadic-functions

helper function to check a value is any of its parameters


I need to check if a value of type T is any of its parameters using a helper function.

For example, using something like the following code

enum class my_enum{k1, k2, k3, k4, k5};
auto v{my_enum::k1};
if (is_any_of(v, my_enum::k1, my_enum::k4, my_enum::k5)) {
}

rather than using if (v == my_enum::k1 || v == my_enum::k4 || v== my_enum::k5) {} or using switch-case.

How do I implement the variadic function bool is_any_of() in C++11?

How the implementation would become simpler with C++17 fold expressions?


Solution

  • This will work in C++11 and will do what you want as long as all of the types can be compared to each other.

    template<typename T, typename R>
    bool is_any_of(T t, R r)
    {
       return t == r;
    }
    
    template<typename T, typename R, typename... ARGS>
    bool is_any_of(T t, R r, ARGS... args)
    {
       if (t == r)
       {
          return true;
       }
       else
       {
          return is_any_of(t, args...);
       }
    }
    

    This is much more compact and will work in C++17

    template<typename T, typename... ARGS>
    bool is_any_of(T t, ARGS... args)
    {
       return ((t == args) || ...);
    }