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

/ 4,990评论 / 17199阅读 / 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. naga169说道:

    Link exchange is nothing else however it is simply placing the other person’s blog link on your page at proper place and other person will also do same in support
    of you.

  2. naga169说道:

    Link exchange is nothing else however it is just placing the other person’s weblog
    link on your page at appropriate place and other person will also do similar
    in favor of you.

  3. naga169说道:

    I pay a quick visit everyday some sites and websites to read content, except
    this webpage presents feature based articles.

  4. tektok说道:

    I really like what you guys are up too. This kind of clever work and reporting!
    Keep up the good works guys I’ve added you guys to our blogroll.

  5. naga169说道:

    Hi there friends, its impressive post regarding educationand fully explained, keep it up all the time.

  6. ufo5555说道:

    Hey are using WordPress for your site platform?
    I’m new to the blog world but I’m trying to get started and create my own. Do you require
    any coding knowledge to make your own blog? Any
    help would be greatly appreciated!

  7. winning303说道:

    Your means of telling all in this article is in fact pleasant,
    every one can without difficulty understand it, Thanks a lot.

  8. naga169说道:

    It’s actually a great and useful piece of information. I’m satisfied that you simply shared this useful info with us.
    Please keep us informed like this. Thanks for sharing.

  9. ufoo555说道:

    Hello there, You have done an incredible job.
    I’ll certainly digg it and personally suggest to my friends.
    I’m confident they will be benefited from this website.

  10. winning303说道:

    Appreciating the time and effort you put into your blog and in depth information you provide.
    It’s great to come across a blog every once in a while that isn’t the same out of date rehashed information. Great read!
    I’ve saved your site and I’m including your RSS feeds to my Google account.

  11. Tekisha说道:

    Greetings! Very helpful advice in this particular post!

    It is the little changes which will make the most significant changes.
    Many thanks for sharing!

  12. DarrelTrini说道:

    en iyi slot siteleri 2024: deneme bonusu veren siteler – slot casino siteleri

  13. Backpage说道:

    Great article. I’m experiencing many of these issues as well..

  14. KevinOvems说道:

    https://sweetbonanza.network/# sweet bonanza demo oyna

  15. DarrelTrini说道:

    slot kumar siteleri: slot siteleri bonus veren – deneme veren slot siteleri

  16. Twenty years again IT firms hardly ever had any presence in India and for that reason weren’t a part of the indices.

  17. Let’s start with how to sign up for your own PayPal account.

  18. If you do not take control of your individual retirement investing and educate yourself on different funding options you’ll lose purchasing power and your retirement accounts will most likely lose another 30 – 40 like we just saw with a few of the foremost financial problems we’re seeing.

  19. Moreover, in the world of business customer happiness yields benefit for the firms.

  20. Hence you can take different control options, like calling a maintenance company to check your stove or checking with your neighbor if you can use his/her stove in case yours fail.

  21. KevinOvems说道:

    https://slotsiteleri.bid/# guvenilir slot siteleri 2024

  22. DarrelTrini说道:

    slot casino siteleri: en guvenilir slot siteleri – deneme bonusu veren siteler

  23. DarrelTrini说道:

    en iyi slot siteleri 2024: slot oyun siteleri – slot siteleri

  24. DarrelTrini说道:

    en iyi slot siteler: en yeni slot siteleri – deneme bonusu veren siteler

  25. Hello there! I could have sworn I’ve been to this web site before but after browsing through a few of the articles I realized it’s new to me. Anyways, I’m definitely delighted I discovered it and I’ll be book-marking it and checking back often.

  26. DarrelTrini说道:

    en iyi slot siteleri 2024: slot siteleri guvenilir – slot siteleri guvenilir

  27. DarrelTrini说道:

    deneme bonusu veren slot siteleri: casino slot siteleri – slot kumar siteleri

  28. KevinOvems说道:

    http://sweetbonanza.network/# sweet bonanza demo

  29. DarrelTrini说道:

    guvenilir slot siteleri 2024: deneme bonusu veren siteler – en iyi slot siteleri 2024

  30. KevinOvems说道:

    https://slotsiteleri.bid/# canl? slot siteleri

  31. Hi, I do believe this is an excellent website. I stumbledupon it 😉 I will return once again since I saved as a favorite it. Money and freedom is the greatest way to change, may you be rich and continue to help other people.

  32. bobres-iptv说道:

    Wonderful article! We are linking to this particularly great post on our website. Keep up the good writing.

  33. cbd oil说道:

    An outstanding share! I’ve just forwarded this onto a coworker who had been conducting a little research on this. And he in fact bought me dinner due to the fact that I found it for him… lol. So let me reword this…. Thank YOU for the meal!! But yeah, thanks for spending some time to talk about this topic here on your website.

  34. fun88说道:

    นี่เป็นบทความที่เขียนได้ดีและให้ข้อมูลดีมาก ฉันได้เรียนรู้อะไรมากมายจากการอ่านบทความนี้

  35. 推す说道:

    Chen was open about his plans for BlackBerry upon becoming a member of the company, saying his intent to maneuver away from hardware manufacturing to deal with enterprise software program corresponding to QNX, BlackBerry UEM, and AtHoc.

  36. Murray — like Briggs, Budd, and Hayes — provided a design service to shoppers like Graham who have been too small to make use of a full-time styling operation.

  37. 建つ说道:

    One of the exchange’s largest brokerage firms, Moore & Schley, was closely in debt and in danger of collapse.

  38. Treasury Secretary Timothy Geithner, then President and CEO of the NY Federal Reserve Bank, placed significant blame for the freezing of credit score markets on a “run” on the entities in the “parallel” banking system, additionally referred to as the shadow banking system.

  39. To see who has despatched you money, visit the Activity tab on the Cash App residence display screen.

  40. winbox88 Login说道:

    Next time I read a blog, Hopefully it doesn’t fail me just as much as this particular one. After all, I know it was my choice to read, but I actually thought you would have something interesting to talk about. All I hear is a bunch of crying about something that you can fix if you weren’t too busy seeking attention.

  41. BaddieHub说道:

    BaddieHub You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!

  42. Aw, this was a really nice post. Spending some time and actual effort to create a really good article… but what can I say… I procrastinate a lot and never seem to get nearly anything done.

  43. Профессиональный сервисный центр по ремонту ноутбуков и компьютеров.дронов.
    Мы предлагаем:починка ноутбука
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  44. Профессиональный сервисный центр по ремонту сотовых телефонов, смартфонов и мобильных устройств.
    Мы предлагаем: ремонт телефона
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  45. DarrelTrini说道:

    yasal slot siteleri: slot siteleri guvenilir – guvenilir slot siteleri 2024

发表回复

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