Bool技巧和模板模板参数

时间:2017-02-18 22:25:15

标签: c++ templates c++14 variadic-templates template-templates

考虑bool技巧来检查一堆类型是否都是相同的类型:

template<typename Type, typename... Types>
static constexpr bool allOf = std::is_same<
    std::integer_sequence<bool, true, std::is_same<Type, Types>::value...>,
    std::integer_sequence<bool, std::is_same<Type, Types>::value..., true>
>::value;

作为示例,可以使用它来检查所有参数是否为int值:

template<typename... Args>
void f(Args&&... args) {
    static_assert(allOf<int, Args...>, "!");
    // ...
}

有没有办法将它与给定模板模板参数的特化一起使用?
例如,使用以下代码:

template<typename> struct S {};

template<typename... Args>
void f(Args&&... args) {
    static_assert(allOf<S, Args...>, "!");
    // ...
}

allOf变量应定义为:

template<template<typename> class Type, typename... Types>
static constexpr bool allOf = ???;

我想检查T中的每个TypesS<U>形式的特化,无论U是什么。

有可能吗?

2 个答案:

答案 0 :(得分:5)

我们只需要检查专业化:

template <class T, template <class...> class Z>
struct isZ : std::false_type { };

template <class... Args, template <class...> class Z>
struct isZ<Z<Args...>, Z> : std::true_type  { };

allOf的更通用的实现:

template <bool... bs>
using allOf = std::is_same<
    std::integer_sequence<bool, true, bs...>,
    std::integer_sequence<bool, bs..., true>>;

有了这个:

static_assert(allOf<isZ<decay_t<Args>, S>::value...>::value, "!");

答案 1 :(得分:1)

如下?

template <typename>
struct S
 { };

template <template <typename> class, typename>
struct isS
 { static constexpr bool value { false } ; };

template <template <typename> class S, typename U>
struct isS<S, S<U>>
 { static constexpr bool value { true } ; };

template<template<typename> class Type, typename... Types>
static constexpr bool allOf = std::is_same<
    std::integer_sequence<bool, true, isS<Type, Types>::value...>,
    std::integer_sequence<bool, isS<Type, Types>::value..., true>
>::value;