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

/ 2,377评论 / 9074阅读 / 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. Arnoldscava说道:

    buying from online mexican pharmacy mexico drug stores pharmacies mexico pharmacy

  2. RichardMonge说道:

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

  3. Waynetar说道:

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

  4. DominicHOr说道:

    purple pharmacy mexico price list: purple pharmacy mexico price list – mexican pharmaceuticals online

  5. Waynetar说道:

    mexican rx online: pharmacies in mexico that ship to usa – buying from online mexican pharmacy

  6. DominicHOr说道:

    mexico drug stores pharmacies: mexico drug stores pharmacies – pharmacies in mexico that ship to usa

  7. Arnoldscava说道:

    mexican pharmacy п»їbest mexican online pharmacies buying prescription drugs in mexico

  8. Arnoldscava说道:

    pharmacies in mexico that ship to usa buying prescription drugs in mexico mexican drugstore online

  9. RichardMonge说道:

    https://mexicandeliverypharma.online/# medicine in mexico pharmacies

  10. Arnoldscava说道:

    mexican rx online pharmacies in mexico that ship to usa mexican drugstore online

  11. DominicHOr说道:

    mexico drug stores pharmacies: mexican online pharmacies prescription drugs – reputable mexican pharmacies online

  12. Waynetar说道:

    buying prescription drugs in mexico online: mexican border pharmacies shipping to usa – mexican border pharmacies shipping to usa

  13. Hi, i believe that i saw you visited my blog so i got here to “go back the favor”.I’m attempting to to find issues to enhance my site!I guess its good enough to use a few of your concepts!!

  14. Waynetar说道:

    buying prescription drugs in mexico: mexico pharmacies prescription drugs – mexican border pharmacies shipping to usa

  15. DominicHOr说道:

    best online pharmacies in mexico: mexico drug stores pharmacies – buying prescription drugs in mexico

  16. RichardMonge说道:

    https://mexicandeliverypharma.online/# best online pharmacies in mexico

  17. Arnoldscava说道:

    mexican rx online mexican drugstore online mexico pharmacies prescription drugs

  18. DominicHOr说道:

    mexico pharmacies prescription drugs: best online pharmacies in mexico – mexican rx online

  19. Waynetar说道:

    pharmacies in mexico that ship to usa: pharmacies in mexico that ship to usa – mexican rx online

  20. DominicHOr说道:

    buying prescription drugs in mexico online: medicine in mexico pharmacies – medicine in mexico pharmacies

  21. Arnoldscava说道:

    mexican pharmacy mexican online pharmacies prescription drugs mexican rx online

  22. RichardMonge说道:

    https://mexicandeliverypharma.com/# buying prescription drugs in mexico online

  23. Arnoldscava说道:

    pharmacies in mexico that ship to usa п»їbest mexican online pharmacies mexican border pharmacies shipping to usa

  24. RichardMonge说道:

    https://mexicandeliverypharma.com/# mexico drug stores pharmacies

  25. DominicHOr说道:

    purple pharmacy mexico price list: buying prescription drugs in mexico – mexican rx online

  26. Thank you for sharing excellent informations. Your web site is so cool. I am impressed by the details that you’ve on this website. It reveals how nicely you perceive this subject. Bookmarked this web page, will come back for extra articles. You, my pal, ROCK! I found just the info I already searched everywhere and just couldn’t come across. What a great site.

  27. Waynetar说道:

    best online pharmacies in mexico: medicine in mexico pharmacies – mexican mail order pharmacies

  28. Arnoldscava说道:

    best online pharmacies in mexico pharmacies in mexico that ship to usa buying from online mexican pharmacy

  29. RichardMonge说道:

    https://mexicandeliverypharma.online/# buying from online mexican pharmacy

  30. prodentim review说道:

    Wow! This blog looks just like my old one! It’s on a completely different subject but it has pretty much the same page layout and design. Wonderful choice of colors!

  31. Next time I read a blog, Hopefully it doesn’t fail me just as much as this one. After all, Yes, it was my choice to read, nonetheless I truly believed you would probably have something interesting to talk about. All I hear is a bunch of crying about something that you can fix if you were not too busy seeking attention.

  32. fitspresso说道:

    Real clean internet site, regards for this post.

  33. Sugar Defender说道:

    This is very interesting, You are a very skilled blogger. I have joined your rss feed and look forward to seeking more of your fantastic post. Also, I’ve shared your site in my social networks!

  34. Klikx说道:

    I seriously love your blog.. Excellent colors & theme. Did you create this site yourself? Please reply back as I’m wanting to create my own blog and would love to find out where you got this from or what the theme is named. Cheers!

  35. casino说道:

    homosexual porn

  36. RobertLAr说道:

    doxycycline 20 mg cost: generic doxycycline – doxycycline buy online us

  37. Soundcloudto.com说道:

    You are so cool! I don’t suppose I have read a single thing like this before. So great to discover another person with original thoughts on this subject matter. Seriously.. many thanks for starting this up. This web site is one thing that is required on the web, someone with some originality.

  38. RobertLAr说道:

    cost of doxycycline 40 mg: can you buy doxycycline over the counter canada – doxycycline 50 medicine

  39. RobertLAr说道:

    where to buy clomid without insurance: where can i buy cheap clomid without prescription – where buy generic clomid price

  40. mp3 juice说道:

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

  41. washi tape说道:

    Good post. I learn something totally new and challenging on blogs I stumbleupon every day. It will always be useful to read through content from other authors and use a little something from other web sites.

  42. link bokep说道:

    You’ve made some good points there. I checked on the web for more info about the issue and found most individuals will go along with your views on this website.

  43. memek说道:

    I would like to thank you for the efforts you’ve put in penning this blog. I’m hoping to see the same high-grade content from you in the future as well. In fact, your creative writing abilities has inspired me to get my own website now 😉

  44. Good web site you have got here.. It’s hard to find excellent writing like yours nowadays. I seriously appreciate people like you! Take care!!

  45. The very next time I read a blog, Hopefully it won’t fail me as much as this particular one. After all, Yes, it was my choice to read, however I actually thought you would probably have something useful to talk about. All I hear is a bunch of crying about something that you could possibly fix if you were not too busy seeking attention.

发表回复

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