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

/ 4,775评论 / 16788阅读 / 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. Card game说道:

    This website was… how do I say it? Relevant!! Finally I have found something which helped me. Many thanks.

  2. Charlestaf说道:

    cheapest online pharmacy india top 10 online pharmacy in india Online medicine order

  3. Michaelpiepe说道:

    mail order pharmacy india: indian pharmacy online – pharmacy website india

  4. DavidWaype说道:

    best canadian pharmacy: canadianpharmacymeds com – canadian pharmacies that deliver to the us

  5. DavidWaype说道:

    reputable indian pharmacies: online pharmacy india – top 10 online pharmacy in india

  6. Michaelpiepe说道:

    buy medicines online in india: mail order pharmacy india – top online pharmacy india

  7. AI for Kids说道:

    I love reading through a post that will make people think. Also, many thanks for allowing for me to comment.

  8. DavidWaype说道:

    reputable indian pharmacies: india pharmacy mail order – top online pharmacy india

  9. Charlestaf说道:

    canadian world pharmacy canada pharmacy 24h cheapest pharmacy canada

  10. Michaelpiepe说道:

    canadian pharmacy: canadapharmacyonline legit – canadian pharmacy online store

  11. EdwardKib说道:

    https://canadapharmast.com/# canadian pharmacy world

  12. DavidWaype说道:

    medication from mexico pharmacy: mexico pharmacy – mexico pharmacies prescription drugs

  13. Charlestaf说道:

    mexican mail order pharmacies mexico pharmacy purple pharmacy mexico price list

  14. Charlestaf说道:

    best canadian pharmacy online canadian online pharmacy canadian pharmacy 24h com safe

  15. EdwardKib说道:

    https://canadapharmast.online/# best mail order pharmacy canada

  16. Charlestaf说道:

    mexican online pharmacies prescription drugs buying prescription drugs in mexico mexico drug stores pharmacies

  17. DavidWaype说道:

    india pharmacy: reputable indian pharmacies – Online medicine home delivery

  18. DavidWaype说道:

    canada discount pharmacy: canadian king pharmacy – canada drugs online reviews

  19. Michaelpiepe说道:

    canadian pharmacy king reviews: canadian pharmacy checker – best mail order pharmacy canada

  20. DavidWaype说道:

    canadian pharmacy world reviews: online canadian pharmacy – trusted canadian pharmacy

  21. hishypesports说道:

    This blog was… how do I say it? Relevant!! Finally I have found something which helped me. Cheers!

  22. bruit societe说道:

    Oh my goodness! Impressive article dude! Thank you, However I am going through issues with your RSS. I don’t understand the reason why I cannot subscribe to it. Is there anybody else getting similar RSS issues? Anyone that knows the answer will you kindly respond? Thanx.

  23. lgbt porn说道:

    homosexual porn

  24. This is a topic that’s close to my heart… Best wishes! Exactly where are your contact details though?

  25. tubidy说道:

    I like it when folks come together and share ideas. Great site, continue the good work.

  26. iwin68说道:

    I used to be able to find good info from your content.

  27. memek说道:

    This is a topic that is close to my heart… Cheers! Exactly where can I find the contact details for questions?

  28. mycroxyproxy说道:

    Hi my loved one I wish to say that this post is amazing nice written and include approximately all vital infos Id like to peer more posts like this

  29. ngentot pepek说道:

    This is a topic that is near to my heart… Many thanks! Where can I find the contact details for questions?

  30. ngentot说道:

    Excellent write-up. I definitely love this website. Keep it up!

  31. porn说道:

    I really like reading through a post that will make men and women think. Also, thank you for allowing me to comment.

  32. link bokep说道:

    I enjoy looking through a post that will make people think. Also, many thanks for allowing for me to comment.

  33. Hello there! I simply want to give you a huge thumbs up for the great info you have got right here on this post. I will be coming back to your web site for more soon.

  34. 부천노래방说道:

    Hi there! This blog post could not be written any better! Going through this post reminds me of my previous roommate! He always kept talking about this. I most certainly will send this information to him. Fairly certain he’ll have a very good read. Many thanks for sharing!

  35. minimalist logo说道:

    Hi there! This article could not be written any better! Going through this article reminds me of my previous roommate! He continually kept talking about this. I most certainly will send this post to him. Pretty sure he’ll have a good read. Thanks for sharing!

  36. AI Meets AI Book说道:

    Good day! I simply want to offer you a big thumbs up for the excellent information you have right here on this post. I am returning to your web site for more soon.

  37. STIKES说道:

    Hi, I do believe this is an excellent website. I stumbledupon it 😉 I may revisit once again since I book-marked it. Money and freedom is the greatest way to change, may you be rich and continue to guide other people.

  38. xxx说道:

    untrustable

  39. FIP UMJ说道:

    Very nice article. I certainly love this website. Stick with it!

  40. This excellent website really has all of the info I needed concerning this subject and didn’t know who to ask.

  41. I blog often and I genuinely appreciate your content. The article has really peaked my interest. I’m going to bookmark your website and keep checking for new details about once per week. I subscribed to your RSS feed as well.

  42. tubidy说道:

    I’m amazed, I must say. Seldom do I encounter a blog that’s equally educative and entertaining, and without a doubt, you have hit the nail on the head. The issue is an issue that not enough men and women are speaking intelligently about. Now i’m very happy I found this in my search for something concerning this.

  43. Good post. I learn something totally new and challenging on blogs I stumbleupon everyday. It’s always useful to read through articles from other authors and practice a little something from their websites.

发表回复

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