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

/ 4,978评论 / 17166阅读 / 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. HermanKak说道:

    buying from online mexican pharmacy: mexican online pharmacies prescription drugs – buying from online mexican pharmacy

  2. Tpower Singapore说道:

    Hi! I could have sworn I’ve visited this web site before but after looking at many of the articles I realized it’s new to me. Anyways, I’m certainly happy I came across it and I’ll be book-marking it and checking back regularly!

  3. Robertkaw说道:

    https://mexstarpharma.online/# mexican border pharmacies shipping to usa

  4. Techno rozen说道:

    Techno rozen Good post! We will be linking to this particularly great post on our site. Keep up the great writing

  5. JeremyRiz说道:

    https://easyrxindia.com/# top 10 pharmacies in india

  6. JeremyRiz说道:

    https://easyrxcanada.online/# canadianpharmacymeds

  7. AnthonyFUS说道:

    world pharmacy india world pharmacy india indian pharmacy

  8. temp-mail说道:

    Your writing is not only informative but also incredibly inspiring. You have a knack for sparking curiosity and encouraging critical thinking. Thank you for being such a positive influence!

  9. best movies说道:

    Hello! I could have sworn I’ve visited this site before but after browsing through a few of the articles I realized it’s new to me. Nonetheless, I’m certainly pleased I discovered it and I’ll be bookmarking it and checking back often.

  10. AnthonyFUS说道:

    buying from online mexican pharmacy buying from online mexican pharmacy mexican drugstore online

  11. Robertkaw说道:

    https://mexstarpharma.com/# mexico pharmacies prescription drugs

  12. Robertkaw说道:

    https://easyrxcanada.online/# ed meds online canada

  13. AnthonyFUS说道:

    indian pharmacy india online pharmacy top 10 pharmacies in india

  14. Robertkaw说道:

    http://easyrxcanada.com/# my canadian pharmacy rx

  15. JeremyRiz说道:

    http://mexstarpharma.com/# mexican border pharmacies shipping to usa

  16. Robertkaw说道:

    https://mexstarpharma.com/# п»їbest mexican online pharmacies

  17. JeremyRiz说道:

    https://easyrxindia.com/# cheapest online pharmacy india

  18. Hey there! I just want to offer you a big thumbs up for your great info you have got right here on this post. I’ll be returning to your site for more soon.

  19. real estate maps说道:

    Real Estate This is my first time pay a quick visit at here and i am really happy to read everthing at one place

  20. I like it when individuals come together and share opinions. Great site, stick with it.

  21. Sight Care说道:

    Hello There. I found your weblog the usage of msn. This is an extremely neatly written article. I will be sure to bookmark it and return to learn extra of your helpful info. Thanks for the post. I will certainly comeback.

  22. After going over a few of the blog articles on your web site, I honestly appreciate your technique of blogging. I saved it to my bookmark website list and will be checking back soon. Please check out my website as well and tell me what you think.

  23. Sv370说道:

    Good post. I learn something new and challenging on websites I stumbleupon on a daily basis. It will always be useful to read through articles from other authors and use something from other websites.

  24. Fitspresso说道:

    I¦ve been exploring for a little for any high quality articles or blog posts on this sort of house . Exploring in Yahoo I at last stumbled upon this site. Studying this information So i am happy to exhibit that I have an incredibly just right uncanny feeling I came upon just what I needed. I such a lot definitely will make sure to don¦t fail to remember this site and provides it a glance regularly.

  25. Very good information. Lucky me I discovered your site by chance (stumbleupon). I’ve saved as a favorite for later!

  26. Ive read several just right stuff here Certainly price bookmarking for revisiting I wonder how a lot effort you place to create this kind of great informative website

  27. google spam说道:

    Hello! I just wish to offer you a huge thumbs up for your great info you have here on this post. I will be returning to your blog for more soon.

  28. 구글SEO说道:

    Great job on explaining this complex topic!프라그마틱

  29. DanielDrync说道:

    cytotec abortion pill https://tamoxifen.bid/# tamoxifen menopause
    buy lasix online

  30. DanielDrync说道:

    Cytotec 200mcg price http://lipitor.guru/# lipitor 20 mg pill
    lasix 100 mg tablet

  31. I blog frequently and I genuinely appreciate your information. This article has really peaked my interest. I’m going to bookmark your website and keep checking for new information about once a week. I opted in for your RSS feed as well.

  32. JamesRok说道:

    lowest price lipitor: Lipitor 10 mg price – lipitor 80 mg cost

  33. JamesRok说道:

    lipitor 40 mg cost: Lipitor 10 mg price – buy lipitor 40 mg

  34. Java Burn说道:

    I’m truly enjoying the design and layout of your website. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a designer to create your theme? Fantastic work!

  35. Dino Game 26说道:

    I blog quite often and I truly thank you for your information. The article has truly peaked my interest. I am going to bookmark your blog and keep checking for new information about once a week. I opted in for your Feed too.

  36. DanielDrync说道:

    buy cytotec over the counter https://lipitor.guru/# lipitor brand
    generic lasix

  37. JamesRok说道:

    buy cytotec pills: Misoprostol price in pharmacy – order cytotec online

  38. Good info. Lucky me I recently found your blog by accident (stumbleupon). I’ve book-marked it for later.

  39. tubidy说道:

    Pretty! This has been an extremely wonderful article. Thanks for providing this info.

  40. JamesRok说道:

    tamoxifen joint pain: Purchase Nolvadex Online – tamoxifen breast cancer prevention

  41. JamesRok说道:

    п»їcytotec pills online: buy cytotec online – purchase cytotec

  42. DanielDrync说道:

    cytotec abortion pill https://lisinopril.guru/# lisinopril 10 12.55mg
    lasix generic

  43. JamesRok说道:

    buy cheap lipitor: buy lipitor 20mg – lipitor otc

  44. DanielDrync说道:

    buy cytotec https://lisinopril.guru/# buy cheap lisinopril 40mg
    lasix online

  45. Ny weekly说道:

    Ny weekly This is really interesting, You’re a very skilled blogger. I’ve joined your feed and look forward to seeking more of your magnificent post. Also, I’ve shared your site in my social networks!

  46. minihints说道:

    Obrigado, estou procurando informações sobre esse tópico há algum tempo e a sua é a melhor que descobri até agora. Mas e em relação aos resultados financeiros? Você tem certeza sobre o fornecimento

发表回复

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