Search code examples
c++variadic-templatestemplate-meta-programming

Is Parameter pack contained in other Parameter pack


I'm writing a class that manages a function object(for fun:)).

I want a templated member function of a templated class to check if all of the types given to it were already given to the class.

template<typename... Args>
class funclass
{
    public:
    template<typename... types>
    void funfun ()
    {
        static_assert(/*is every type in types contained in Args*/);
    }
};

Solution

  • You can use a helper to check if a given T is part of the Args... pack:

    template <typename T, typename ...Args>
    struct contains {
        static constexpr bool value = (std::is_same<T,Args>::value || ...);
    };
    

    Then check it for all types in types...:

    template<typename... Args>
    struct funclass
    {
        template<typename... types>
        void funfun ()
        {
            constexpr bool contains_all = (contains<types,Args...>::value && ...);
            static_assert( contains_all  );
        }
    };
    
    int main() {
        funclass<int,double>{}.funfun<int>(); // OK
        funclass<int,double>{}.funfun<float>(); // error
    }