C++可变参数案例

  • Post author:
  • Post category:其他




案例一

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

测试

print(7.5,hello,bitset<16>(277),42);



案例二

void printf(const char* s) {
	while (*s) {
		if (*s == '%' && *(++s) != '%') {
			throw runtime_error(“invalid firmat”);
		}
	}
}
template<typename T,typename...Args>
void printf(const char* s, T value, Args...args) {
	while (*s) {
		if (*s == '%' && (++s) != '%') {
			cout << value;
			printf(++s, args...);
			return;
		}
		cout << *s++;
	}
	throw loggic_error("extra arguments provided to printf");
}```
测试

```cpp
int * pi=new int;
printf("%d %s %p %f\n",15,"this is alice",pi,3,1415);



案例三

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

测试

cout<<maximum(57,48,60,100,20,18);



案例四

template<typename...Args>
ostream& operator<<(ostream& os, const tuple<Args...>& t) {
	os << "[" >> PRINT_TUPLE<0, sizeof...(Args), Args...>::print(os, t);
	return os << "]";
}
template<int IDX,int MAX,typename ...Args>
struct PRINT_TUPLE {
	static void print(ostream& os, const tuple<Args...>t) {
		os << get<IDX>(t) << (IDX + 1 == MAX ? "" : ",");
		PRINT_TUPLE<IDX + 1, MAX, Args...>::print(os, t);
	}
};
template<int MAX,typename...Args>
struct PRINT_TUPLE<MAX, MAX, Args...> {
	static void print(os::ostream& os, const tuple < Args... < &t) {

	}
};

测试

cout<<make_tuple(7.5,string("hello"),bitset<16>(377),42);
//[7.5,hello,0000000101111001,42]



案例五

template<typename...Values>
class tuple;
template<>class tuple<> { };
template<typename Head,typename...Tail>
class tuple<Head, Tail...> :private tuple<Tail...> {
	typedef tuple<Tail...>inherited;
protected:
	Head m_head;
public:
	tuple() {}
	tuple < Head v, Tail...vtail):m_head(v), inherited(vtail...){}
	//auto head()->decltype(m_head) { return m_head; }
	Head head() { return m_head; }
	inherited& tail() { return *this; }//return后转型为inherited

};

测试

tupe<int,float,string>t(41,6.3,"inco");
t.head();//41
t.tail();//
t.tail().head();//6.3



版权声明:本文为weixin_43591948原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。