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

/ 4,967评论 / 17142阅读 / 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. Douglasnug说道:

    buy prescription drugs from india: online pharmacy india – mail order pharmacy india

  2. Leonardskarm说道:

    https://mexicopharmacy.win/# mexican online pharmacies prescription drugs

  3. Leonardskarm说道:

    http://edpillpharmacy.store/# cost of ed meds

  4. download youtube说道:

    I quite like looking through a post that will make people think. Also, thank you for permitting me to comment.

  5. Douglasnug说道:

    buying prescription drugs in mexico online: Certified Mexican pharmacy – mexican pharmaceuticals online

  6. Douglasnug说道:

    buy ed pills online: best ed pills online – edmeds

  7. Leonardskarm说道:

    http://indiapharmacy.shop/# reputable indian online pharmacy

  8. Leonardskarm说道:

    http://mexicopharmacy.win/# reputable mexican pharmacies online

  9. Douglasnug说道:

    mexican rx online: mexico pharmacies prescription drugs – mexican pharmaceuticals online

  10. Douglasnug说道:

    mexican drugstore online: Mexico pharmacy online – mexico pharmacies prescription drugs

  11. Leonardskarm说道:

    https://mexicopharmacy.win/# buying prescription drugs in mexico

  12. Douglasnug说道:

    india online pharmacy: indian pharmacy online – indianpharmacy com

  13. Leonardskarm说道:

    https://mexicopharmacy.win/# mexican online pharmacies prescription drugs

  14. Everything is very open with a very clear explanation of the issues. It was definitely informative. Your site is very useful. Thanks for sharing!

  15. Leonardskarm说道:

    http://edpillpharmacy.store/# online ed treatments

  16. Douglasnug说道:

    cheap boner pills: ED meds online with insurance – where can i get ed pills

  17. Douglasnug说道:

    erectile dysfunction online prescription: ed pills online – cheapest online ed meds

  18. This, and reasonable valuations will help hinder major stock market downside over the near term.

  19. Douglasnug说道:

    buy ed medication: Best ED pills non prescription – edmeds

  20. Candy and chocolate bars are enjoyed by children and adults the world over, but how well do you know your favorite candies?

  21. Tulip mania Bubble 1637 Dutch Republic A bubble (1633-37) in the Dutch Republic during which contracts for bulbs of tulips reached extraordinarily high prices, and suddenly collapsed.

  22. largehints说道:

    olá, gosto muito da sua escrita, então compartilhe, mantemos uma correspondência extra sobre sua postagem na AOL. Preciso de um especialista nesta casa para desvendar meu problema. Talvez seja você. Olhando para frente para vê-lo

  23. Douglasnug说道:

    indianpharmacy com: Best Indian pharmacy – indian pharmacy online

  24. Douglasnug说道:

    mexico pharmacies prescription drugs: Certified Mexican pharmacy – purple pharmacy mexico price list

  25. Increasingly, baby boomers are turning to the Internet for news, getting information from government Web sites and downloading music.

  26. Leonardskarm说道:

    http://edpillpharmacy.store/# erectile dysfunction online

  27. Douglasnug说道:

    buying from online mexican pharmacy: mexico pharmacies prescription drugs – mexican mail order pharmacies

  28. This quantity will probably be reversed once the genuine public sale bills are debited from your account.

  29. Leonardskarm说道:

    http://mexicopharmacy.win/# mexican mail order pharmacies

  30. minihints说道:

    obviously like your website but you need to test the spelling on quite a few of your posts Several of them are rife with spelling problems and I to find it very troublesome to inform the reality on the other hand Ill certainly come back again

  31. Douglasnug说道:

    mexican drugstore online: Purple pharmacy online ordering – mexican rx online

  32. de esta fuente说道:

    Hello there! I could have sworn I’ve visited this blog before but after browsing through some of the posts I realized it’s new to me. Anyways, I’m certainly delighted I came across it and I’ll be book-marking it and checking back frequently!

  33. Leonardskarm说道:

    http://indiapharmacy.shop/# best online pharmacy india

  34. I?¦ve been exploring for a little for any high-quality articles or blog posts in this sort of area . Exploring in Yahoo I finally stumbled upon this website. Reading this information So i?¦m happy to exhibit that I’ve an incredibly just right uncanny feeling I found out just what I needed. I most undoubtedly will make certain to don?¦t overlook this site and provides it a glance regularly.

  35. Sugar Defender说道:

    Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your blog? My blog is in the exact same area of interest as yours and my visitors would definitely benefit from some of the information you present here. Please let me know if this alright with you. Appreciate it!

  36. Douglasnug说道:

    online ed drugs: Cheapest online ED treatment – erectile dysfunction online

  37. Douglasnug说道:

    indian pharmacy: indian pharmacy – india pharmacy mail order

  38. Douglasnug说道:

    medicine in mexico pharmacies: Best pharmacy in Mexico – buying prescription drugs in mexico

  39. Douglasnug说道:

    pharmacies in mexico that ship to usa: Best online Mexican pharmacy – mexican border pharmacies shipping to usa

  40. Leonardskarm说道:

    https://indiapharmacy.shop/# top online pharmacy india

  41. Leonardskarm说道:

    https://indiapharmacy.shop/# Online medicine home delivery

  42. Douglasnug说道:

    purple pharmacy mexico price list: Medicines Mexico – purple pharmacy mexico price list

  43. Douglasnug说道:

    best online pharmacies in mexico: Mexico pharmacy online – mexican border pharmacies shipping to usa

  44. I really like looking through a post that will make people think. Also, thanks for allowing me to comment.

  45. CharlesLem说道:

    https://indiapharmacy.shop/# buy prescription drugs from india
    cheapest ed online

  46. Douglasnug说道:

    erectile dysfunction drugs online: online ed prescription same-day – п»їed pills online

  47. Leonardskarm说道:

    http://mexicopharmacy.win/# mexican drugstore online

发表回复

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