原文地址:http://bbs.gimoo.net/thread/166549-1.html
引注:作者太多,没法一一署名,都是常用的。也欢迎大家共享,我会整理进去。
《Effective C++》条款02指出:你可以获得宏带来的效率以及一般函数的所有可预料行为和类型安全性(type safety)——只要你写出template inline函数。
那么,有哪些template inline值得我们在实际工程中运用呢?
希望借集体的力量,能收集到大量实用的内联函数模板函数。
这是目前我暂时能想到的,抛砖引玉,请大家不吝赐教!
- C/C++ code
- templateinline void SafeDelete(T*& p)
- { delete p; p = 0; }
- templateinline void SafeDeleteArray(T*& p)
- { delete[] p; p = 0; }
- template inline void UnusedVar(const T&)
- {}
- template inline size_t CountOf(const T& array)
- { UnusedVar(array); return sizeof(array) / sizeof(array[0]); }
- template inline const T& Max(const T& a, const T& b)
- { return a > b ? a : b; }
- template inline const T& Min(const T& a, const T& b)
- { return a < b ? a : b; }
- template inline void Swap(T& a, T& b)
- { T t(a); a = b; b = t; }
C/C++ code
//按内存方式强制类型转换,如将type (CLS::*pf)(type par)强制转换为void *: void
//按内存方式强制类型转换,如将type (CLS::*pf)(type par)强制转换为void *: void
- *p = GetCast(pf);
- template
- DEST GetCast(const SRC& src)
- {
- union
- {
- SRC src;
- DEST dest;
- }myunion = {src};
- return myunion.dest;
- }
发个我常用的单键类吧.
- C/C++ code
- #ifndef __SINGLE_H__
- #define __SINGLE_H__
- #include
- template class TSingle
- {
- public:
- inline static T* Create()
- {
- if (!spT_)
- {
- spT_ = new(&sMemory_) T;
- }
- return spT_;
- }
- inline static T* Instance()
- {
- return spT_;
- }
- inline static void Destroy()
- {
- if (spT_)
- {
- spT_->~T();
- spT_ = 0;
- }
- }
- private:
- typedef union
- {
- char t_[sizeof(T)];
- short int shortInt_;
- int int_;
- long int longInt_;
- float float_;
- double double_;
- long double longDouble_;
- }UNMaxAlign;
- static UNMaxAlign sMemory_;
- static T* spT_;
- };
- template typename
- TSingle::UNMaxAlign TSingle::sMemory_;
- template typename
- T* TSingle::spT_ = 0;
- #endif // __SINGLE_H__
C/C++ code
//注意:请不要用于指针之间的转换,特别是BSTR
//注意:请不要用于指针之间的转换,特别是BSTR
- template
- lType TranslateType(rType& rValue, IsDiff& isDiff)
- {
- stringstream is;
- lType lValue;
- is > lValue;
- return lValue;
- };
C/C++ code
- template
- struct is_a_ptr
- {
- enum{ yes = FALSE };
- };
- template
- struct is_a_ptr
- {
- enum{ yes = TRUE };
- };
- template
- inline void UnusedVar(const T&)
- {
- if(is_a_ptr::yes)
- throw std:: invalid_argument("Not a array!");
- }
- template
- inline size_t CountOf(const T& array)
- {
- UnusedVar(array);
- return sizeof(array) / sizeof(array[0]);
- }
- ///
- int main()
- {
- try
- {
- int a[10];
- int b[11][12];
- int *c;
- cout
CountOf那个函数模板是不是这么来实现更好点呢?
- C/C++ code
- template
- inline size_t CountOf(const T(&)[N])
- {
- return N;
- }
C/C++ code
//判断参数类型是否是无符号类型,当然只限于有序类型
//判断参数类型是否是无符号类型,当然只限于有序类型
- template
- inline bool IsUnsigned(T)
- {
- return ((T)-1 > 0);
- }
C/C++ code
- template
- inline size_t CountOf(const T(&)[N])
- {
- return N;
- }
- //直接这么用就可以了:
- int a[9];
- char aa[10][11];
- CountOf(a);//返回9
- CountOf(aa);//返回10