1. 程式人生 > >C++11 變參模板(variadic templates)

C++11 變參模板(variadic templates)

Variadic Template是C++11的一個很重要的特性;

變體現在兩個方面:

(1)引數個數:利用引數個數逐一遞減的特性,實現遞迴呼叫;

(2)引數型別:引數個數逐一遞減導致引數型別也逐一遞減;


兩個注意點

(1)遞迴呼叫

(2)遞迴終止:使用過載的辦法終止遞迴呼叫;


舉兩個例子

1.print函式

///  Variadic template
//過載的遞迴終止函式
void printX() {

}

template<typename T,typename...Types>
void printX(const T& firstArg, const Types&...args) {
	cout << firstArg << endl;
	printX(args...);
}


int main()
{
	printX(7.5, "hello", bitset<16>(377), 42);
	return 0;
}

2. max函式

//過載的遞迴終止條件
int maximun(int n){
	return n;
}

template<typename...Args>
int maximun(int n,Args...args){
	return std::max(n,maximun(args...));
}

int main()
{
	//C++11之後已經支援了多個數求最大值的操作,使用initializer_list
	//cout << max({ 57,48,60,100,20,18 });
	cout<<maximun(57,48,60,100,20,18)<<endl;
	return 0;
}
有一篇寫的不錯的部落格可參考: http://www.cnblogs.com/qicosmos/p/4325949.html