参数包是否包含在其他参数包中

Is Parameter pack contained in other Parameter pack

我正在写一个 class 来管理一个函数对象(为了好玩:))。

我想要模板化 class 的模板化成员函数来检查是否所有提供给它的类型都已经提供给 class。

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

您可以使用助手来检查给定的 T 是否属于 Args... 包:

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

然后检查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
}

如果你也想强制它们的顺序相同,你可以生成两个tuple类型然后比较它们,如下

#include <type_traits>
#include <tuple>
template<typename... Args>
struct Fun{
    template<typename... types>
    void fun (){
        static_assert(std::is_same_v<std::tuple<Args...>,std::tuple<types...>>);
    }
};
int main(){
    Fun<int,bool>{}.fun<int, bool>();//passes
    Fun<int,bool>{}.fun<int, bool, double>();//fails

}