[c++模板] 用可变参数模板来实现 printf

/ 6,181评论 / 22279阅读 / 3点赞

模板

// 普通函数, 只能接受 int 类型参数,如果传入其他类型需要类型转换
int sum(int a, int b) {
    return (a + b);
}

double sum(double a, double b) {
    return (a + b);
}
// 模板
template<typename T>
T sum(T a, T b) {
    return (a + b);
}

// 编译会生成:
int sum(int a, int b) {
    return (a + b);
}
double sum(double a, double b) {
    return (a + b);
}

可变参数模板

int sum(int a, int b, int c) {
    return (a + b + c);
}

int sum(int a, int b, int c, int d) {
    return (a + b + c + d);
}
// ......
template<typename T>
T sum(T... args) {
    // 展开求和
}
template<typename T>
T mysum(T item) {
    return item;
}
template<typename T>
T mysum(T item, T... args) {
    return mysum(item) + mysum(args);
}
/// 入口
template<typename T>
T sum(T... args) {
    return mysum(args);
}
int sum(int arg0, int arg1, int arg2, int arg3, int arg4);
int mysum(int item, int arg1, int arg2, int arg3, int arg4);
int mysum(int item);
int mysum(int item, int arg2, int arg3, int arg4);
int mysum(int item, int arg3, int arg4);
int mysum(int item, int arg4);

不定类型数量

template<typename T1, typename T2, typename ...Args>
T1 mysum(T2 item, Args... args);

实现printf

template<typename T>
int printNum(const std::string& str, int index, T&& item) {
	auto doShift = true;
	while (index < str.size()) {
		if (index == (str.size() - 1) || str[index] != '%') {
			cout << str[index];
			++index;
		}
		else if(doShift) {
			doShift = false;
			++index;
			switch (str[index]) {
			case 's':
			case 'd':
				cout << item;
				break;
			}
			++index;
		}
		else {
			return index - 1;
		}
	}
	return index - 1;
}

template<typename T, typename... Args>
int printNum(const std::string& str, int index, T&& item, Args&&... args) {
	index = printNum(str, index, item);
	return printNum(str, index + 1, std::forward<Args>(args)...);
}

template<typename ...Args>
void myPrintNum(const std::string& str, Args&&... args) {
	int index = 0;
	while (index < str.size()) {
		if (str[index] != '%') {
			cout << str[index];
			++index;
		}
		else {
			break;
		}
	}
	index = printNum(str, index, std::forward<Args>(args)...);
	++index;
	while (index < str.size()) {
		cout << str[index];
		++index;
	}
}

int main() {

        // 调用,参数数量允许和字符串内数量不同,不会出错
	myPrintNum("output: %d, %d, %d, %d  ---", 123, 100.123, true);
	return 0;
}
  1. SamuelDarse说道:

    amoxicillin 500mg no prescription: how to buy amoxycillin – buy amoxicillin from canada

  2. Danielplent说道:

    http://prednibest.com/# prednisone 20mg price

  3. KennethCex说道:

    how can i get cheap clomid without a prescription clomid on pharm buying cheap clomid without dr prescription

  4. メタボ体系说道:

    Chartres Cathedral, Passion of Christ windows, (c.

  5. In March 2020 with the passage of 2020 Act 12, the first election was postponed to June 2, 2020, to permit for mail in ballots and pre-canvassing.

  6. This web page was final edited on 5 June 2023, at 00:35 (UTC).

  7. Maya Nilsen is probably one of the most acquainted faces in fashion, on Youtube or off it.

  8. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт телефонов nothing, можете посмотреть на сайте: ремонт телефонов nothing
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  9. Предлагаем услуги профессиональных инженеров офицальной мастерской.
    Еслли вы искали ремонт телефонов samsung цены, можете посмотреть на сайте: ремонт телефонов samsung в москве
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  10. You can comply with Pia Wurtzbach on her Instagram account right here.

  11. DWB Editor Anthony Brown, who had attended UEA, prompt the location after one other had fallen via, because the distinctive Ziggurat-formed scholar residences Norfolk and Suffolk Terrace echoed pyramid motifs within the script.

  12. The intelligence gathered by Reed and others led Washington to abandon the idea of attacking at Mount Holly, and he started focusing as an alternative on concentrating on the Hessian garrison in Trenton.

  13. This improved function in the web retail sector in India has attracted tens of millions of NRIs, who’re going surfing sitting anyplace in the world for a style of Indian attire and accessories.

  14. Without it, one might have difficulty accounting for a large number of human acts which (let me be charitable) owe little to ratiocination, despite the satisfaction we take in our reason.

  15. 10 homes of worship, including: American Presbyterian Church, B’nai Abraham Synagogue, Christ Episcopal Church, Dorothea Dix Unitarian Universalist Group, Ebenezer Full Gospel Neighborhood Church, First Baptist Church of Bordentown, First Presbyterian Church, Mount Zion AME Church, Saint Mary’s Roman Catholic Church, Shiloh Baptist Church, Trinity United Methodist Church and Union Baptist Church.

  16. RobertInpup说道:

    non prescription prednisone 20mg: Predni Best – prednisone for sale

  17. Good web site you have here.. It’s hard to find high quality writing like yours these days. I seriously appreciate individuals like you! Take care!!

  18. Danielplent说道:

    http://clomidonpharm.com/# how to buy cheap clomid without prescription

  19. KennethCex说道:

    buy cheap amoxicillin Amox Star amoxicillin generic

  20. SamuelDarse说道:

    cost of cheap clomid: clomid no prescription – clomid online

  21. Very good info. Lucky me I discovered your website by chance (stumbleupon). I’ve saved it for later.

  22. Danielplent说道:

    http://prednibest.com/# prednisone tablets

  23. SamuelDarse说道:

    where can you buy amoxicillin over the counter: amoxicillin 500 tablet – amoxicillin 1000 mg capsule

  24. KennethCex说道:

    buy cipro cheap CiPharmDelivery ciprofloxacin generic

  25. RobertInpup说道:

    ciprofloxacin: CiPharmDelivery – cipro pharmacy

  26. iwin说道:

    I truly love your website.. Pleasant colors & theme. Did you make this website yourself? Please reply back as I’m planning to create my very own site and would like to find out where you got this from or just what the theme is named. Appreciate it.

  27. Migueldit说道:

    https://amoxstar.com/# medicine amoxicillin 500

  28. Counties directly to its west (in each Tennessee and Alabama) use the Central Time Zone.

  29. KennethCex说道:

    can i order clomid for sale how can i get clomid without insurance how to buy clomid without rx

  30. RobertInpup说道:

    can you buy clomid without prescription: order clomid prices – where buy generic clomid online

  31. SamuelDarse说道:

    prednisone 5mg coupon: Predni Best – 25 mg prednisone

  32. Migueldit说道:

    http://amoxstar.com/# where can i buy amoxicillin online

  33. Danielplent说道:

    https://clomidonpharm.com/# can i order clomid without prescription

  34. Good day! I simply would like to give you a huge thumbs up for your excellent information you’ve got right here on this post. I am returning to your website for more soon.

  35. KennethCex说道:

    can you buy amoxicillin over the counter in canada AmoxStar cost of amoxicillin 875 mg

  36. SamuelDarse说道:

    price of prednisone 5mg: PredniBest – prednisone without prescription medication

  37. Danielplent说道:

    https://amoxstar.com/# amoxicillin order online no prescription

  38. RobertInpup说道:

    prednisone 10mg tabs: prednisone 5443 – prednisone 50mg cost

  39. Very good post. I will be experiencing some of these issues as well..

  40. KennethCex说道:

    buy cipro cipro online no prescription in the usa ciprofloxacin generic price

  41. Danielplent说道:

    http://clomidonpharm.com/# can i get generic clomid without insurance

  42. KennethCex说道:

    buy cheap amoxicillin AmoxStar where can i buy amoxocillin

  43. RobertInpup说道:

    can you buy prednisone online uk: Predni Best – prednisone tabs 20 mg

  44. Danielplent说道:

    https://prednibest.com/# steroids prednisone for sale

  45. snaptik说道:

    Excellent post. I am experiencing a few of these issues as well..

  46. KennethCex说道:

    can you buy amoxicillin over the counter AmoxStar amoxicillin 500 mg tablet

  47. Danielplent说道:

    https://prednibest.com/# purchase prednisone 10mg

  48. KennethCex说道:

    fast shipping prednisone prednisone 50mg cost 5 mg prednisone tablets

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注