Modern C++ design 第二章

一,编译期asset

二,local class , 可以替代匿名命名空间, 让其不可见

class Interface
{
public:
   virtual void Fun() = 0;
   ...
};
template <class T, class P>
Interface* MakeAdapter(const T& obj, const P& arg)
{
   class Local : public Interface
   {
   public:
      Local(const T& obj, const P& arg)
         : obj_(obj), arg_(arg) {}
      virtual void Fun()
      {
         obj_.Call(arg_);
      }
   private:
      T obj_;
      P arg_;
   };
   return new Local(obj, arg);
}

三,int to type

template <int v>
struct Int2Type
{
   enum { value = v };
};
template <typename T, bool isPolymorphic>
class NiftyContainer
{
private:
   void DoSomething(T* pObj, Int2Type<true>)
   {
      T* pNewObj = pObj->Clone();
      ... polymorphic algorithm ...
   }
   void DoSomething(T* pObj, Int2Type<false>)
   {
      T* pNewObj = new T(*pObj);
      ... nonpolymorphic algorithm ...
   }
public:
   void DoSomething(T* pObj)
   {
      DoSomething(pObj, Int2Type<isPolymorphic>());
   }
};

四,type to type(可以作为函数的参数使之重载)

template <typename T>
struct Type2Type
{
   typedef T OriginalType;
};
// An implementation of Create relying on overloading
//      and Type2Type
template <class T, class U>
T* Create(const U& arg, Type2Type<T>)
{
return new T(arg);
}
template <class U>
Widget* Create(const U& arg, Type2Type<Widget>)
{
return new Widget(arg, -1);
}


string* pStr = Create("Hello", Type2Type<string>());
Widget* pW = Create(100, Type2Type<Widget>());


五,type selection(通过萃取)

萃取:template<T>struct /class 中typedef, (本次例子中,重载了模板函数)。然后其他template使用的时候,动态使用之前typedef的类型


template <typename T, bool isPolymorphic>
struct NiftyContainerValueTraits
{
   typedef T* ValueType;
};
template <typename T>
struct NiftyContainerValueTraits<T, false>
{
   typedef T ValueType;
};
template <typename T, bool isPolymorphic>
class NiftyContainer
{
   ...
   typedef NiftyContainerValueTraits<T, isPolymorphic>
      Traits;
   typedef typename Traits::ValueType ValueType;
};

This way 

 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值