对模板中的每个其他类型执行static_assert

Do static_assert on every other type in a template

本文关键字:执行 类型 static assert 其他      更新时间:2023-10-16

如何对模板中的其他类型执行static_assert s(或其他检查)?

template<typename... Ts> //T1,T2,T3,...
struct foo {
  //How can I
  //for T1,T3,T5,T7,...
  //do some checks, for example:
  //static_assert(std::is_default_constructible<Tn>::value,"invalid type");
  //static_assert(std::is_copy_constructible<Tn>::value,"invalid type");
};

请尝试以下操作:

#include <type_traits>
template <typename... Ts>
struct default_constructible;
template <typename T>
struct default_constructible<T>
{
    static constexpr bool value = std::is_default_constructible<T>::value;
};
template <>
struct default_constructible<>
{
    static constexpr bool value = true;
};
template <typename T, typename U, typename... Ts>
struct default_constructible<T, U, Ts...>
{
    static constexpr bool value = std::is_default_constructible<T>::value && default_constructible<Ts...>::value;
};
template <typename... Ts>
struct foo
{
    static_assert(default_constructible<Ts...>::value, "");
};
class A { A() = delete; };
template class foo<int, bool>;      // Compiles
template class foo<int, bool, A>; // Does not compile

演示

你可以试试这个:

template <template <typename...> class Pred, typename ...Args> struct check_odd;
template <template <typename...> class Pred>
struct check_odd<Pred> : std::true_type { };
template <template <typename...> class Pred, typename T>
struct check_odd<Pred, T> : Pred<T> { };
template <template <typename...> class Pred, typename T1, typename T2, typename ...Args>
struct check_odd<Pred, T1, T2, Args...>
{
    static constexpr bool value = Pred<T1>::value && check_odd<Pred, Args...>::value;
};

用法:

static_assert(check_odds<std::is_arithmetic, T1, T2, T3, T4, T5, T6>::value,
              "Not all odd types are arithmetic.");

明显的泛化途径是对组合器进行参数化(目前硬编码为"AND"或&&),并为谓词提供额外的参数。