对模板中的每个其他类型执行static_assert
Do static_assert on every other type in a template
如何对模板中的其他类型执行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"或&&
),并为谓词提供额外的参数。
相关文章:
- 在C++中对T*类型执行std::move的意外行为
- 仅在函数模板中为那些定义了函数的类型执行函数
- C++将一个指针分配给另一个指针时执行的类型检查
- C++如何乘以包含 std::variant 元素的向量的迭代器?正在执行迭代器类型的转换?
- 当前不会命中断点。没有调试器目标代码类型的可执行代码与此文件关联
- Eclipse 可执行架构类型
- 如何检查参数包是否具有执行顺序中的确切类型
- 如何对模板类型强制执行常量
- 执行特定函数取决于类型
- 动态控制C++的执行策略类型
- 根据运行时提供的类型执行模板函数
- 如何在执行期间终止(或返回)具有结构类型的自动函数
- 如何动态执行具有任意参数类型的函数指针
- VIM:执行复杂文件类型的脚本和显示结果
- 根据类模板的类型参数自动执行类模板的大小参数
- 如何执行两个函数参数具有相同的模板类型
- C++ 11/14 根据模板类型在单个函数中执行不同的操作
- C++ 仅当模板为字符串类型时执行小写转换
- 有没有一种好的方法可以在C++中的可变模板中对函数参数强制执行类型限制
- 为什么编译器不执行类型转换?