c++ - 对模板中的所有其他类型执行 static_assert

标签 c++ templates c++11

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

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

Demo

关于c++ - 对模板中的所有其他类型执行 static_assert,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17350329/

相关文章:

时间:2019-03-08 标签:c++system()raisesENOMEM

c++ - 在 C++ 中跨多个文件使用相同的变量

c++ - 在C++中将对象写入二进制文件

.net - 在 .NET 中生成简单报告的模板引擎

python - timedelta() Python Django 的格式显示

c++ - 了解 C++11 中的 <system_error> 工具

c++ - 具有数组构造函数方法的 constexpr 类

c++ - TinyXml++ 和 Visual C++ Express Edition 2008 的链接问题

java - 解析格式错误的 HTML 文档

c++ - 模板参数组合排序