如何静态断言元组的所有类型是否满足某些条件?

How to static assert whether all types of a tuple fulfill some condition?

我有一些类型特征 SomeTraits,我可以从中提取类型 T 是否通过 SomeTraits<T>::value 满足某些条件。 如何遍历给定 std::tuple<> 的所有类型并检查(通过静态断言)它们是否都满足上述条件?例如

using MyTypes = std::tuple<T1, T2, T3>;
// Need some way to do something like
static_assert(SomeTupleTraits<MyTypes>::value, "MyTypes must be a tuple that blabla...");

其中 SomeTupleTraits 将检查 MyTypes 中的每种类型是否 SomeTraits<T>::value == true?

我仅限于 C++14。

作为一行(换行符可选),你可以这样做:

// (c++20)
static_assert([]<typename... T>(std::type_identity<std::tuple<T...>>) {
    return (SomeTrait<T>::value && ...);
}(std::type_identity<MyTypes>{}));

或者您可以创建辅助特征来执行此操作:

// (c++17)
template<template<typename, typename...> class Trait, typename Tuple>
struct all_of;

template<template<typename, typename...> class Trait, typename... Types>
struct all_of<Trait, std::tuple<Types...>> : std::conjunction<Trait<Types>...> {};

static_assert(all_of<SomeTrait, MyTypes>::value);

或者在 C++11 中,您可以在 helper trait 中重新实现 std::conjunction

template<template<typename, typename...> class Trait, typename Tuple>
struct all_of;

template<template<typename, typename...> class Trait>
struct all_of<Trait, std::tuple<>> : std::true_type {};

template<template<typename, typename...> class Trait, typename First, typename... Rest>
struct all_of<Trait, std::tuple<First, Rest...>> :
    std::conditional<bool(Trait<First>::value),
                     all_of<Trait, std::tuple<Rest...>>,
                     std::false_type>::type::type {};

static_assert(all_of<SomeTrait, MyTypes>::value, "");