检查嵌套混合中每个类的类型特征
Check a type trait of every class in a nested mixin
我有一个混合的集合,每个混合体都有一个类型特征。我想检查布尔值的值以及每个混合的这种特征的值。例如,如果我有一个Mixin1<Mixin2<T> >
并且Mixin1<T>
有is_nice == true
而Mixin2<T>
有is_nice == false
,那么嵌套混合蛋白的特征应该计算为"假"。
#include <iostream>
// A type trait to determine if a type is nice
template <typename T>
struct is_nice
{
static const bool value = false;
};
// Base case
template <class T>
struct is_nice_all {
static_assert(is_nice<typename T::FieldsType>::value, "Not nice!");
static const bool value = is_nice<typename T::FieldsType>::value;
};
template <template <class> class Outer, class Inner>
struct is_nice_all<Outer<Inner> > {
// AND the result of the niceness of the current mixin and the next mixin, recursively
static const bool value = is_nice< typename Outer<Inner>::FieldsType >::value && is_nice_all<Inner>::value;
};
class BaseClass
{
public:
using FieldsType = BaseClass;
};
template <>
struct is_nice<BaseClass>
{
static const bool value = true;
};
class Mixin1_Fields
{
public:
int property1;
};
template<class MixinBase>
class Mixin1 : public MixinBase, public Mixin1_Fields
{
public:
using FieldsType = Mixin1_Fields;
};
template <>
struct is_nice<Mixin1_Fields>
{
static const bool value = true;
};
class Mixin2_Fields
{
public:
int property2;
};
template<class MixinBase>
class Mixin2 : public MixinBase, public Mixin2_Fields
{
public:
using FieldsType = Mixin2_Fields;
};
template <>
struct is_nice<Mixin2_Fields>
{
static const bool value = true;
};
class Mixin3_Fields
{
public:
int property3;
};
template<class MixinBase>
class Mixin3 : public MixinBase, public Mixin3_Fields
{
public:
using FieldsType = Mixin3_Fields;
};
template <>
struct is_nice<Mixin3_Fields>
{
static const bool value = false;
};
int main()
{
std::cout << is_nice_all<Mixin1<Mixin2<BaseClass> > >::value << std::endl;
std::cout << is_nice_all<Mixin1<Mixin3<BaseClass> > >::value << std::endl;
return 0;
}
这是"奇怪"还是合理的做法?我没有看到很多关于在线使用这样的混合 - 这种添加属性的模式在实践中不经常使用吗?
您不想对自身进行递归,而只想在Inner
上执行递归,并对当前类型使用常规值
template <template <class> class Outer, class Inner>
struct is_nice_all<Outer<Inner> > {
// AND the result of the niceness of the current mixin and the next mixin, recursively
static const bool value = is_nice<typename Outer<Inner>::FieldsType>::value
&& is_nice_all<Inner>::value;
};
相关文章:
- 根据C++标准的定义实现"is_similar"类型特征
- C++类型特征,以查看是否可以<uint32_t>对类型"K"的任何变量调用"static_cast(k)"
- C ++类型特征:确保子类实现方法
- 根据类型特征更改函数定义?
- 如何使用类型特征将函数的通用引用参数限制为 r 值引用?
- 在C++中创建新的类型特征
- 如何构造一个类型特征,可以判断一个类型的私有方法是否可以在另一个类型的构造函数中调用?
- std::begin-类型特征中未考虑用户定义的重载
- 在类型特征修改后,无法限定类型
- 使用类型特征的部分类专用化
- 为什么不调用预期的函数?我是否对类型特征的理解不正确?
- 了解类型特征的体系结构
- 为什么使用某些类型特征的模板类型会导致模板扣除失败
- 有了C++类型特征,有没有办法避免铸造
- 哪种类型特征表明该类型是可分配的?(元组,对)
- 一种类型特征,标识哪个类提供通过重载解析选择的函数
- 如何使用类型特征正确推断引用的参数
- 如何通过扩展以下类型特征来删除 decltype(&MyClass::funct) 部分?
- 从标准库类型特征继承
- 为什么类型特征不适用于命名空间范围内的类型?