【问题标题】:Type Traits check OF CRTP Derived , in base class ,issue is undefined typeCRTP派生的类型特征检查,在基类中,问题是未定义的类型
【发布时间】:2019-08-27 13:29:39
【问题描述】:

寻找像下面的 EvalDelay 这样的解决方案来解决未定义类型的问题 EvalDelay 是我尝试解决问题,但没有工作

由于在派生的基类中检查了特征,派生仍然未定义 问题是我如何用一些模板魔法来延迟评估

这里的特征检查很简单,它只是检查的基础。

 struct Base{};

 template<class T_Type>
 struct T_CheckTrait
 {
    static const bool bVal = std::is_base_of_v<Base, T_Type>;   
  };

template<class TypeToDelay, class T = Next> 
struct EvalDelay
{
    //using type = std::add_volatile<TypeToDelay>;      
    //using type = typename type_identity<TypeToDelay>::type;

    using type = TypeToDelay;
};

 template<class T_Derived>
 struct RexBase
  {
       using T_TypeDly = typename EvalDelay<T_Derived>::type;
       static const bool bVal = T_CheckTrait<T_TypeDly>::bVal;
  };


  struct Rex:RexBase<Rex>{   };

void Main 
    {
    Rex Obj; //and on compilation i get error undefined type, not here but in templates above    

    }

无法编译,因为我试图在编译时检查其基类中 Rex 的特征。

寻找模板魔法来延迟评估

std::add_volatile 确实会延迟评估,如 EvalDelay 所示,但它会将其延迟到运行时,寻找编译时评估但延迟了。

谢谢

【问题讨论】:

标签: c++ templates lazy-evaluation traits crtp


【解决方案1】:

不确定您的最终目标是什么,但以下是延迟评估类型特征的方法:

#include <type_traits>

struct Base {};

template<class T>
struct EvalDelay
{
    using type = T;
};

template<class T_Derived>
struct RexBase
{
    using is_base = typename EvalDelay<std::is_base_of<Base, T_Derived>>::type;
};

struct Rex : RexBase<Rex> {   };
struct Rex2 : RexBase<Rex2>, Base {   };

int main()
{
    Rex Obj;
    static_assert(Rex::is_base::value == false, "Rex is not Base");
    static_assert(Rex2::is_base::value == true, "Rex2 is Base");
}

Live demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 2011-02-01
    • 1970-01-01
    相关资源
    最近更新 更多