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

/ 4,975评论 / 17161阅读 / 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. JamesRok说道:

    furosemide 40 mg: buy furosemide – furosemida 40 mg

  2. DanielDrync说道:

    buy cytotec https://cytotec.pro/# cytotec pills buy online
    furosemide 100 mg

  3. Next time I read a blog, I hope that it does not fail me just as much as this one. I mean, Yes, it was my choice to read, nonetheless I truly believed you would have something useful to talk about. All I hear is a bunch of crying about something that you can fix if you weren’t too busy looking for attention.

  4. JamesRok说道:

    tamoxifen breast cancer prevention: buy tamoxifen citrate – tamoxifen postmenopausal

  5. JamesRok说道:

    Abortion pills online: cheapest cytotec – cytotec buy online usa

  6. Hey there! I simply wish to give you a big thumbs up for your excellent info you have got here on this post. I am coming back to your web site for more soon.

  7. DanielDrync说道:

    cytotec buy online usa https://lipitor.guru/# lipitor generic canada
    lasix medication

  8. JamesRok说道:

    lipitor brand name price: Atorvastatin 20 mg buy online – lipitor for sale

  9. DanielDrync说道:

    buy cytotec https://lipitor.guru/# buy lipitor
    lasix furosemide

  10. best price说道:

    Very nice blog post. I definitely appreciate this site. Stick with it!

  11. JamesRok说道:

    lasix 20 mg: generic lasix – lasix

  12. DanielDrync说道:

    buy cytotec over the counter http://furosemide.win/# lasix medication
    lasix furosemide

  13. JamesRok说道:

    tamoxifen for breast cancer prevention: tamoxifen benefits – natural alternatives to tamoxifen

  14. I really like looking through a post that can make men and women think. Also, thanks for permitting me to comment.

  15. Hiya, I am really glad I’ve found this information. Today bloggers publish just about gossips and web and this is actually irritating. A good site with interesting content, this is what I need. Thank you for keeping this site, I will be visiting it. Do you do newsletters? Can’t find it.

  16. DanielDrync说道:

    п»їcytotec pills online https://cytotec.pro/# buy cytotec pills online cheap
    furosemide 100 mg

  17. JamesRok说道:

    cytotec abortion pill: Misoprostol price in pharmacy – Abortion pills online

  18. JamesRok说道:

    buy furosemide online: cheap lasix – lasix online

  19. The venture capital investors are another type of debt financing.

  20. For some people, federal student loans won’t cover all of college, and so financial aid advisers tend to suggest using federal loans as ways to close the gap between tuition and fees and scholarship and grant money.

  21. Venezuela is to start selling its cryptocurrency “Petro” next month.

  22. The rationale of a rolling turbo arises from a combination of a predictable course process of the base value stock and the promise of a proportionally higher profit than would be possible with the purchase of the base stock.

  23. These companies have significant ideas and professional group members but are usually lacking in the financial capital needed.

  24. DanielDrync说道:

    buy cytotec over the counter http://tamoxifen.bid/# tamoxifen alternatives
    lasix side effects

  25. DanielDrync说道:

    purchase cytotec http://lisinopril.guru/# price of lisinopril 5mg
    furosemide 100 mg

  26. Hotels说道:

    An impressive share! I’ve just forwarded this onto a coworker who had been conducting a little homework on this. And he in fact bought me dinner due to the fact that I discovered it for him… lol. So allow me to reword this…. Thanks for the meal!! But yeah, thanx for spending some time to discuss this subject here on your web site.

  27. JamesRok说道:

    lipitor 80 mg: Atorvastatin 20 mg buy online – buy lipitor online uk

  28. important link说道:

    You have made some really good points there. I checked on the net to find out more about the issue and found most people will go along with your views on this web site.

  29. DanielDrync说道:

    buy cytotec over the counter https://lisinopril.guru/# prinivil 40 mg
    lasix generic name

  30. StephenJonge说道:

    https://lipitor.guru/# buy lipitor from india

  31. StephenJonge说道:

    https://furosemide.win/# lasix dosage

  32. JamesRok说道:

    medicine lisinopril 10 mg: Buy Lisinopril 20 mg online – lisinopril 20 mg price in india

  33. JamesRok说道:

    lipitor 10mg price australia: cheapest ace inhibitor – where to buy lipitor

  34. Excellent blog you have got here.. It’s hard to find excellent writing like yours these days. I honestly appreciate individuals like you! Take care!!

  35. JamesRok说道:

    cytotec online: cheapest cytotec – order cytotec online

  36. JamesRok说道:

    cost of lipitor in mexico: price canada lipitor 20mg – buy generic lipitor online

  37. DanielDrync说道:

    buy cytotec in usa http://lisinopril.guru/# lisinopril brand name in india
    lasix dosage

  38. StephenJonge说道:

    http://tamoxifen.bid/# tamoxifen dose

  39. StephenJonge说道:

    https://tamoxifen.bid/# nolvadex pills

  40. DanielDrync说道:

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

  41. JamesRok说道:

    nolvadex d: buy tamoxifen online – tamoxifen for men

  42. StephenJonge说道:

    http://tamoxifen.bid/# tamoxifen for men

  43. youtube to mp4说道:

    I like looking through a post that can make people think. Also, thank you for allowing me to comment.

  44. DanielDrync说道:

    cytotec abortion pill https://tamoxifen.bid/# tamoxifen bone density
    lasix uses

  45. You’ve made some good points there. I looked on the web for more information about the issue and found most people will go along with your views on this web site.

  46. JamesRok说道:

    tamoxifen reviews: buy tamoxifen online – clomid nolvadex

  47. JamesRok说道:

    average cost of generic lipitor: buy lipitor 20mg – brand name lipitor price

  48. JamesRok说道:

    buy misoprostol over the counter: buy misoprostol tablet – cytotec online

  49. JamesRok说道:

    cheapest price for lisinopril india: Buy Lisinopril 20 mg online – buy lisinopril without a prescription

发表回复

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