C:如果在traits类或default中可用,则使用inner typedef
发布时间:2020-12-16 09:36:55 所属栏目:百科 来源:网络整理
导读:我目前正在编写一个模板,该模板根据输入的类别进行不同的操作. 有3个案例我想加入我的特质课程. A. The type has a typedef type_category ,use that. B. The type doesn’t have the typedef,use the type regular_tag (most common case) C. My specializa
我目前正在编写一个模板,该模板根据输入的类别进行不同的操作.
有3个案例我想加入我的特质课程.
我该如何管理?做A.和C.或B.和C很简单.但我不知道如何获得所有3. 编辑 一个例子可能会使它更容易理解. class Foo { typedef foo_tag type_category; } class Bar; my_traits<Foo>::type(); // makes a foo_tag my_traits<Bar>::type(); // makes a regular_tag my_traits<std::list<Baz>>::type(); // makes a special_tag because I want special list proce ssing. 解决方法
脚手架可能如下所示:
template <typename T> struct MyTrait { typedef typename MyHelper<T,CheckForType<T>::value>::type tag; }; template <typename T> struct MyTrait<std::list<T>> { typedef special_tag tag; }; 我们需要帮手: template <typename T,bool> struct MyHelper { typedef regular_tag tag; }; template <typename T> struct MyHelper<T,true> { typedef typename T::type_category tag; }; 现在我们需要的是一个类型特征来检查成员typedef: template<typename T> struct CheckForType { private: typedef char yes; typedef struct { char array[2]; } no; template<typename C> static yes test(typename C::type_category*); template<typename C> static no test(...); public: static const bool value = sizeof(test<T>(0)) == sizeof(yes); }; 用法: MyTrait<Foo>::tag (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |