簡體   English   中英

在嵌套的mixin中檢查每個類的類型特征

[英]Check a type trait of every class in a nested mixin

我有一個mixin集合,每個都有定義的類型特征。 我想為每個這些mixin檢查每個特征的布爾AND值。 例如,如果我有一個Mixin1<Mixin2<T> >Mixin1<T>具有is_nice == trueMixin2<T>具有is_nice == false ,則嵌套的mixin的特征應為“ 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;
}

這是“怪異”還是合理的做法? 我看不到在網上使用像這樣的mixin的大量信息-這種添加屬性的模式在實踐中並不常用嗎?

您不想對其本身進行遞歸,而僅對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;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM