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

/ 4,974评论 / 17155阅读 / 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. tech updates说道:

    Excellent blog you’ve got here.. It’s hard to find excellent writing like yours these days. I really appreciate people like you! Take care!!

  2. My spouse and I stumbled over here different page and thought I might check things out. I like what I see so now i am following you. Look forward to looking into your web page yet again.

  3. DanielDrync说道:

    cytotec pills buy online https://lipitor.guru/# lipitor prescription drug
    lasix tablet

  4. StephenJonge说道:

    https://lipitor.guru/# lipitor 40mg

  5. DanielDrync说道:

    buy cytotec pills online cheap https://tamoxifen.bid/# tamoxifen for gynecomastia reviews
    generic lasix

  6. 토토사이트说道:

    You have made some good points there. I checked on the internet for more info about the issue and found most people will go along with your views on this site.

  7. StephenJonge说道:

    http://cytotec.pro/# buy cytotec over the counter

  8. JamesRok说道:

    tamoxifen side effects forum: buy tamoxifen online – tamoxifen and depression

  9. JamesRok说道:

    buy furosemide online: furosemide online – lasix 40 mg

  10. DanielDrync说道:

    buy cytotec in usa http://tamoxifen.bid/# tamoxifen and weight loss
    lasix dosage

  11. StanleyMaf说道:

    Misoprostol 200 mg buy online buy cytotec online buy cytotec pills

  12. JamesRok说道:

    Misoprostol 200 mg buy online: Misoprostol price in pharmacy – Abortion pills online

  13. StephenJonge说道:

    http://furosemide.win/# lasix 20 mg

  14. StephenJonge说道:

    http://lipitor.guru/# lipitor 4 mg

  15. DanielDrync说道:

    Misoprostol 200 mg buy online https://furosemide.win/# furosemide 100 mg
    lasix pills

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

  17. JamesRok说道:

    lasix for sale: cheap lasix – buy furosemide online

  18. JamesRok说道:

    nolvadex for sale: how does tamoxifen work – tamoxifen side effects forum

  19. JamesRok说道:

    buy cytotec in usa: purchase cytotec – buy cytotec

  20. Very good post. I will be dealing with some of these issues as well..

  21. JamesRok说道:

    tamoxifen and uterine thickening: Purchase Nolvadex Online – tamoxifen and weight loss

  22. DanielDrync说道:

    п»їcytotec pills online http://lisinopril.guru/# how to buy lisinopril
    lasix 100mg

  23. Hi there! I could have sworn I’ve been to this site before but after looking at many of the posts I realized it’s new to me. Anyhow, I’m definitely happy I came across it and I’ll be bookmarking it and checking back regularly.

  24. StephenJonge说道:

    https://lipitor.guru/# lipitor drug prices

  25. DanielDrync说道:

    buy cytotec in usa https://lipitor.guru/# generic lipitor for sale
    buy lasix online

  26. May I simply say what a comfort to discover somebody who actually understands what they’re discussing online. You certainly understand how to bring an issue to light and make it important. More people must check this out and understand this side of the story. I was surprised you aren’t more popular since you definitely possess the gift.

  27. The minimum tick is 10 cents.

  28. While you cannot predict the future, you can make sure that you have an understanding of the risks involved in your investment, by employing due diligence, and researching the property market thoroughly.

  29. The tires also contain technology called raindrop grooves — sipes situated deep inside the tire that are designed to channel water on the road surface to the left and to the right, away from the bottom of the tire.

  30. Its geographical area covers most of the urban development agency the Hyderabad Metropolitan Development Authority (HMDA).

  31. Very good write-up. I absolutely appreciate this website. Keep it up!

  32. sbi証券 開設说道:

    Fees can reduce an investor’s profits and potentially reduce the total return below what could be achieved through a less expensive mutual fund or exchange-traded fund (ETF).

  33. StephenJonge说道:

    http://lipitor.guru/# lipitor prescription cost

  34. StanleyMaf说道:

    lisinopril 5mg tablets buy lisinopril lisinopril 80 mg daily

  35. StanleyMaf说道:

    lisinopril 20mg india cheap lisinopril lisinopril 49 mg

  36. DanielDrync说道:

    order cytotec online https://tamoxifen.bid/# tamoxifen hip pain
    furosemida

  37. DanielDrync说道:

    buy cytotec online https://furosemide.win/# lasix 40mg
    lasix 100mg

  38. StephenJonge说道:

    https://tamoxifen.bid/# tamoxifen 20 mg

  39. DanielDrync说道:

    buy cytotec pills online cheap https://tamoxifen.bid/# cost of tamoxifen
    lasix generic

  40. StanleyMaf说道:

    buy lasix online buy furosemide lasix 40mg

  41. StephenJonge说道:

    https://cytotec.pro/# п»їcytotec pills online

  42. prodronessupply说道:

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

  43. DanielDrync说道:

    Cytotec 200mcg price https://tamoxifen.bid/# tamoxifen
    furosemida 40 mg

  44. StephenJonge说道:

    http://lipitor.guru/# price canada lipitor 20mg

  45. JamesRok说道:

    lisinopril 20 mg price: Buy Lisinopril 20 mg online – lisinopril 1.25 mg

  46. The very next time I read a blog, Hopefully it won’t fail me as much as this particular one. After all, I know it was my choice to read, but I genuinely thought you would probably have something helpful to say. All I hear is a bunch of whining about something that you could fix if you weren’t too busy seeking attention.

  47. DanielDrync说道:

    order cytotec online http://tamoxifen.bid/# tamoxifen adverse effects
    lasix medication

  48. DanielDrync说道:

    cytotec online http://lisinopril.guru/# lisinopril 5 mg daily
    lasix

发表回复

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