设为首页 加入收藏

TOP

c++ 泛型 之 TypeTraints
2015-07-20 17:15:51 来源: 作者: 【 】 浏览:2
Tags:泛型 TypeTraints

?

#ifndef TYPETRAITS_H_
#define TYPETRAITS_H_

//只有声明,没有定义,它只能被用来表示“我不是个令人感兴趣的型别”。
class NullType;
//这是一个可被继承的合法型别,而且你可以传递EmptyType对象。
class EmptyType{};

//1. 常整数 映射为型别
/*
根据不同的数值产生不同的型别。一般而言,符合下列条件便可使用Int2Type
1. 有必要根据某个编译期常数调用一个或数个不同的函数
2. 有必要在编译期实施“分派”(dispatch)(if else 型分派要求每个条件都要编译通过,而通过
   Int2Type不会产生类似问题,因为编译期不会去编译一个未被使用到的template函数(如果一个template的
   成员函数未曾被真正使用上,c++不会将它具现化)。
*/
template
  
   
struct Int2Type
{
	enum{value = v};
};

//Type2Type 唯一作用就是消除重载函数的歧义(模棱两可)。
////////////////////////////////////////////////////////////////////////////////
// class template Type2Type
// Converts each type into a unique, insipid type
// Invocation Type2Type
   
     where T is a type // Defines the type OriginalType which maps back to T //////////////////////////////////////////////////////////////////////////////// template 
    
      struct Type2Type { typedef T OriginalType; }; //型别选择,根据第一个引数判断是用第二个参数还是第三个参数 template
     
       struct Select { typedef T Result; }; template
      
        struct Select
       
         { typedef U Result; }; //Type Traits template 
        
          class TypeTraints { private: template
         
          struct PointerTraints { enum{result = false}; typedef NullType PointerType; }; template
          
           struct PointerTraints
           
             { enum{result = true;}; typedef U PointerType; }; template
            
             struct PtoMTraits { enum{result = false}; }; template
             
               struct PtoMTraits
               { enum{result = true}; }; public: enum { isPointer = PointerTraints
               
                ::result, isMemberPointer = PtoMTraits
                
                 ::result }; typedef typename PointerTraints
                 
                  ::PointerType PointerType; }; #endif
                 
                
               
             
            
           
          
         
        
       
      
     
    
   
  

测试

?

void typetraits_test()
{
	const bool isPointer = TypeTraints
   
    ::iterator>::isPointer; }
   


?

?

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇leetcode:Find Peak Element 下一篇[LeetCode]189.Rotate Array

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Redis on AWS:Elast (2025-12-27 04:19:30)
·在 Spring Boot 项目 (2025-12-27 04:19:27)
·使用华为开发者空间 (2025-12-27 04:19:24)
·Getting Started wit (2025-12-27 03:49:24)
·Ubuntu 上最好用的中 (2025-12-27 03:49:20)