对模板中的每个其他类型执行static_assert [英] Do static_assert on every other type in a template

查看:89
本文介绍了对模板中的每个其他类型执行static_assert的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I do static_asserts (or other checks) on every other type in a template?

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

演示

这篇关于对模板中的每个其他类型执行static_assert的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆