0%
Variadic Templates(可变参数模板)
帮助我们实现递归
code
基本使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
void printX(){
}
template <typename T,typename... types>
void printX(const T& firstArg,const Types&... args){ cout<< firstArg<<endl; cout<< sizeof...(args...)<<endl; printX(args...); }
void printX(const Types&... args){ cout<< firstArg<<endl; cout<< sizeof...(args...)<<endl; printX(args...);
}
|
cpp库函数举例
calculate Hash
1 2 3 4 5 6
| #include <functional> template <typename T> inline void hash_combine(size_t& seed,const T& val){ seed^=std::hash<T>()(val)+0x9e3779b9+(seed<<6)+(seed>>2); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
template<typename T,typename.. Type> inline hash_val(size_t& seed, const T& val,const Types&... args){ hash_combine(seed,val); hash_val(seed,args...); }
template <typeame... Types> inline size_t hash_val(const Types&... args){ size_t seed=0; hash_val(seed,args); return seed; }
template <typeame T> inline size_t hash_val(size_t& seed,const T& val){ hash_combine(seed,val); }
|
tuple realise
1 2
| template <typename... Values>class tuple; template <>class tuple<>{};
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| template<typename Head,typename... Tail> class tuple<Head,Tail...>:private typle<Tail...>{ typedef typle<Tail...> inherited; pubic: tuple(){} tuple(Head v,Tail... vtail):m_head(v),inherited(vtail...){} typename Head::type head(){return m_head;} inherited& tail(){return *this;}
protected: Head m_head; };
|
tuple sample
1 2 3 4
| tuple<int,float,string> t(41,6.3,"nico"); t.head(); t.tail().head()
|
nullptr(空指针)
用于区分空指针与NULL
code
1 2 3 4 5
| void f(int a){} void f(void* a){} f(NULL); f(0); f(nullptr);
|
file_name
1 2 3 4 5 6 7
| #if define(__cplusplus)&& __cplusplus>=201103L #ifndef _GXX_NULLPTR_T #define _GXX_NULLPTR_T typedef decltype(nullptr) nullptr_t
#endif
|
auto
在类型繁琐以及无法确定返回参数类型时使用(lambda function)
code
1 2 3 4 5 6
| vector<string> v; auto pos=v.begin(); auto i=[](int x)->bool{
};
|