一,编译期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