我有以下类型函数来计算某种类型
T
是否是元组中类型列表的一部分:
template<typename T, typename Tuple>
struct IsInTuple;
template<typename T, typename ...Ts>
struct IsInTuple<T, std::tuple<Ts...>>
{
static constexpr bool value = std::disjunction_v<std::is_same<T, Ts>...>;
};
我的问题是,是否可以将此函数推广到任何采用可变参数类型列表的可变参数模板类型,以便它不仅适用于元组,而且还适用于变体?
是否可以将此函数推广到任何采用可变参数类型列表的可变参数模板类型,以便它不仅适用于
s,而且还适用于std::tuple
s?std::variant
是的,可以。只需使用模板模板参数来概括情况即可。
template<typename T, typename Class>
struct IsInTypeList;
template<template<typename...Ts> class Class, typename T, typename ...Ts>
struct IsInTypeList<T, Class<Ts...>>
{
static constexpr bool value = (std::is_same_v<T, Ts> || ...);
};
// Example usage
static_assert(IsInTypeList<int, std::tuple<int, float, double>>::value, "int is in the tuple");
static_assert(!IsInTypeList<char, std::tuple<int, float, double>>::value, "char is not in the tuple");
static_assert(!IsInTypeList<char, std::variant<int, float, double>>::value, "char is not in the tuple");