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

/ 4,955评论 / 17117阅读 / 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. Timothyomide说道:

    http://kamagrait.pro/# Farmacia online piГ№ conveniente

  2. Tomasdrads说道:

    viagra naturale: viagra generico – viagra ordine telefonico

  3. Greetings from Florida! I’m bored at work so I decided to check out your website on my iphone during lunch break. I enjoy the info you present here and can’t wait to take a look when I get home. I’m shocked at how fast your blog loaded on my phone .. I’m not even using WIFI, just 3G .. Anyhow, wonderful blog!

  4. RandyBulty说道:

    acquistare farmaci senza ricetta: Cialis generico prezzo – farmaci senza ricetta elenco

  5. tautan saya说道:

    You ought to be a part of a contest for one of the most useful blogs on the net. I am going to recommend this web site!

  6. RandyBulty说道:

    farmacia online piГ№ conveniente: avanafil generico – farmacie online autorizzate elenco

  7. Tomasdrads说道:

    comprare farmaci online all’estero: Avanafil a cosa serve – farmacia online

  8. Tomasdrads说道:

    farmacie online affidabili: avanafil in farmacia – farmaci senza ricetta elenco

  9. Tomasdrads说道:

    Farmacie online sicure: Farmacie online sicure – farmacie online affidabili

  10. Tomasdrads说道:

    comprare farmaci online all’estero: Tadalafil generico migliore – top farmacia online

  11. xxx说道:

    incest porn

  12. Hi, I do believe this is a great web site. I stumbledupon it 😉 I may come back once again since I book-marked it. Money and freedom is the best way to change, may you be rich and continue to help others.

  13. Many thanks for the fantastic post C I’d fun reading it! That i love this blog.

  14. You really make it seem so easy with your presentation but I find this topic to be really something that I think I would never understand. It seems too complex and extremely broad for me. I’m looking forward for your next post, I will try to get the hang of it!

  15. I like this site so much, saved to bookmarks.

  16. Matthewnouts说道:

    order cheap propecia pill: buy propecia tablets – buying cheap propecia without a prescription

  17. LewisToite说道:

    https://propeciabestprice.pro/# buy cheap propecia pills

  18. Matthewnouts说道:

    buy propecia online: cost propecia without a prescription – cost of cheap propecia tablets

  19. Matthewnouts说道:

    get generic propecia price: get cheap propecia – cost generic propecia price

  20. Matthewnouts说道:

    tamoxifen hormone therapy: nolvadex pct – tamoxifen hip pain

  21. Matthewnouts说道:

    cost of cheap propecia without a prescription: cost propecia prices – cost cheap propecia for sale

  22. Matthewnouts说道:

    buy zithromax online cheap: cheap zithromax pills – zithromax cost

  23. LewisToite说道:

    https://prednisonebestprice.pro/# prednisone 10 mg tablets

  24. Matthewnouts说道:

    zithromax online australia: zithromax prescription – zithromax 1000 mg pills

  25. My spouse and i have been so contented Raymond managed to finish off his investigation through the precious recommendations he gained using your web pages. It’s not at all simplistic to just possibly be making a gift of secrets and techniques which often most people have been trying to sell. And we also grasp we have you to be grateful to for this. The specific illustrations you’ve made, the easy blog menu, the relationships you make it easier to instill – it’s got most amazing, and it’s leading our son and us know that the concept is exciting, and that is particularly pressing. Thanks for the whole thing!

  26. LewisToite说道:

    http://prednisonebestprice.pro/# buy prednisone without a prescription

  27. Matthewnouts说道:

    where can i buy prednisone online without a prescription: 10mg prednisone daily – prednisone pack

  28. Matthewnouts说道:

    get cheap propecia pill: get propecia without rx – cost of propecia without insurance

  29. LewisToite说道:

    https://prednisonebestprice.pro/# prednisone 5 tablets

  30. Matthewnouts说道:

    buy misoprostol over the counter: cytotec online – buy cytotec

  31. LewisToite说道:

    http://propeciabestprice.pro/# buying cheap propecia without prescription

  32. Matthewnouts说道:

    ordering prednisone: prednisone 25mg from canada – prednisone 30

  33. baby turbans说道:

    Aw, this was a very good post. Taking a few minutes and actual effort to make a very good article… but what can I say… I hesitate a whole lot and never seem to get nearly anything done.

  34. Matthewnouts说道:

    prednisone buy cheap: purchase prednisone canada – where can i order prednisone 20mg

  35. Matthewnouts说道:

    prednisone 20 mg pill: cost of prednisone – apo prednisone

  36. LewisToite说道:

    http://nolvadexbestprice.pro/# tamoxifen citrate

  37. Matthewnouts说道:

    zithromax cost canada: buy zithromax online fast shipping – buy zithromax online fast shipping

  38. Matthewnouts说道:

    zithromax z-pak price without insurance: order zithromax without prescription – zithromax 250 mg

  39. Matthewnouts说道:

    tamoxifen hot flashes: where can i buy nolvadex – low dose tamoxifen

  40. Matthewnouts说道:

    tamoxifen adverse effects: tamoxifen estrogen – tamoxifen for gynecomastia reviews

  41. LewisToite说道:

    http://nolvadexbestprice.pro/# tamoxifen citrate pct

  42. LewisToite说道:

    http://zithromaxbestprice.pro/# zithromax buy online no prescription

  43. Matthewnouts说道:

    steroids prednisone for sale: prednisone brand name canada – prednisone otc uk

  44. thecroxyproxy说道:

    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

  45. mycroxyproxy说道:

    I was recommended this website by my cousin I am not sure whether this post is written by him as nobody else know such detailed about my difficulty You are wonderful Thanks

  46. LewisToite说道:

    http://zithromaxbestprice.pro/# zithromax generic cost

  47. Matthewnouts说道:

    generic prednisone tablets: 54 prednisone – prednisone oral

发表回复

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