利用模板判断模板参数类型

C++中可以把数据类型当成参数,类型参数可以由编译器推导出来,也可以由程序员显式指定. 下面的两个模板,就可以用来判断模板的类型参数是否为reference或者const.

template <typename T> struct IsReference ///Use this struct to determine if a template type is a reference { enum { VALUE = 0 }; };

template <typename T> struct IsReference<T&> { enum { VALUE = 1 }; };

template <typename T> struct IsReference<const T&> { enum { VALUE = 1 }; };

template <typename T> struct IsConst ///Use this struct to determine if a template type is a const type { enum { VALUE = 0 }; };

template <typename T> struct IsConst<const T&> { enum { VALUE = 1 }; };

template <typename T> struct IsConst<const T> { enum { VALUE = 1 }; };

这两个模板函数(IsReference和IsConst)聪明的地方在于,编译器会根据模板参数的类型,选 择最贴近的模板类(struct)来实例化.

使用示例: template <typename T> void foo() { if (IsReferenc<T>.VALUE) { // 类型参数T为reference } if (IsConst<T>.VALUE) { // 类型参数为const } }

阅读更多

模板推导参数类型错误

03-07

[code=c]rntemplate rnclass CBimapEx2rnrnpublic:rn typedef typename boost::bimap CBimap;rn typedef typename CBimap::value_type BMV_PAIR;rn typedef typename CBimap::left_map::const_iterator BM_LEFT_CITER;rn typedef typename CBimap::right_map::const_iterator BM_RIGHT_CITER;rnpublic:rn CBimap bmValue;rnpublic:rn unsigned int GetCount() return bmValue.size(); rn void InsertValue(const TLeft& left, const TRight& right) bmValue.insert(BMV_PAIR(left, right)); rn void EraseValue(const TLeft& rValue) bmValue.left.erase(rValue); rn void EraseValue(const TRight& rValue) bmValue.right.erase(rValue); rn void Clear() return bmValue.clear(); rn bool GetValue(const TLeft& key, TRight* pValue = NULL)rn rn BM_LEFT_CITER left_iter = bmValue.left.find(key);rn if (left_iter != bmValue.left.end())rn rn if (pValue) *pValue = left_iter->second; rn return true;rn rn return false;rn rn bool GetValue(const TRight& key, TLeft* pValue = NULL)rn rn BM_RIGHT_CITER right_iter = bmValue.right.find(key);rn if (right_iter != bmValue.right.end())rn rn if (pValue) *pValue = right_iter->second; rn return true;rn rn return false;rn rn;rnrnrnrnrntypedef CBimapEx2 CBimapID;rnrnclass Sample:public CBimapIDrnrnrnprivate:// This is singleton pattern trick.rn Sample()rnpublic:rn ~Sample();rnrnpublic:rn // Get the one and only global CResIDrn //static Sample& ResID(); //to testrnrn static Sample& ResID()rn rn static Sample obj;rn return obj;rn rnrnrn long GetID(std::string strID)rn rn long nID = -1;rn GetValue(strID, &nID);rn return nID;rn rnrn std::string GetID(long nID)rn rn std::string strID;rn GetValue(nID, &strID);rn return strID;rn rnrnrn;rnrnrn[/code]rnrn提示错误:rnrnbool CBimapEx2::GetValue(const TLeft &,TRight *)”: 不能将参数 1 从“std::string”转换为“const int &”rnrnlong GetID(std::string strID)rn rn long nID = -1;rn GetValue(strID, &nID); //这里编译不了rn return nID;rn

没有更多推荐了,返回首页