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

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

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

  2. John说道:

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

  3. IWIN说道:

    Next time I read a blog, Hopefully it does not fail me as much as this one. I mean, Yes, it was my choice to read through, nonetheless I actually believed you would probably have something interesting to talk about. All I hear is a bunch of moaning about something that you could possibly fix if you were not too busy seeking attention.

  4. ytmp3说道:

    You’ve made some decent points there. I checked on the net to learn more about the issue and found most individuals will go along with your views on this site.

  5. IWIN CLUB说道:

    Hi there, There’s no doubt that your site may be having internet browser compatibility issues. Whenever I look at your blog in Safari, it looks fine however, when opening in IE, it’s got some overlapping issues. I merely wanted to provide you with a quick heads up! Other than that, fantastic blog!

  6. Very good post. I absolutely appreciate this site. Keep it up!

  7. tubidy mp3说道:

    Everything is very open with a clear explanation of the issues. It was really informative. Your website is extremely helpful. Thanks for sharing!

  8. Your style is really unique in comparison to other people I have read stuff from. Thank you for posting when you have the opportunity, Guess I will just bookmark this blog.

  9. Jamesjer说道:

    buy doxycycline online australia: buy doxycycline south africa – doxycycline nz cost

  10. Way cool! Some extremely valid points! I appreciate you writing this write-up plus the rest of the site is very good.

  11. 博彩社区说道:

    I could not resist commenting. Very well written.

  12. Jamesjer说道:

    cipro online no prescription in the usa: cipro for sale – buy cipro without rx

  13. Jamesjer说道:

    can i purchase clomid without prescription: how can i get cheap clomid price – can i buy cheap clomid tablets

  14. Jamesjer说道:

    can i buy amoxicillin over the counter in australia: generic amoxil 500 mg – amoxicillin from canada

  15. Brooks Donnelly说道:

    There is definately a great deal to find out about this issue. I love all the points you’ve made.

  16. Jamesjer说道:

    doxycycline prescription cost uk: doxycycline in mexico – doxycycline medication pills

  17. orionservice说道:

    Magnificent beat I would like to apprentice while you amend your site how can i subscribe for a blog web site The account helped me a acceptable deal I had been a little bit acquainted of this your broadcast offered bright clear idea

  18. this article说道:

    You’re so awesome! I don’t suppose I’ve read a single thing like that before. So great to discover someone with original thoughts on this subject. Really.. thank you for starting this up. This site is something that’s needed on the internet, someone with a bit of originality.

  19. online slot说道:

    porn cannibalism

  20. Jamesjer说道:

    buy cipro online without prescription: buy cipro online – buy cipro online canada

  21. ThomasInace说道:

    https://doxycyclinedelivery.pro/# doxycycline hydrochloride 100mg

  22. Jamesjer说道:

    amoxicillin 500mg buy online uk: amoxicillin 500mg capsule cost – amoxicillin capsule 500mg price

  23. ThomasInace说道:

    https://amoxildelivery.pro/# generic for amoxicillin

  24. ThomasInace说道:

    http://paxloviddelivery.pro/# Paxlovid over the counter

  25. Good information. Lucky me I found your blog by accident (stumbleupon). I’ve bookmarked it for later!

  26. ThomasInace说道:

    http://paxloviddelivery.pro/# paxlovid pharmacy

  27. Jamesjer说道:

    doxycycline tablets australia: cost of doxycycline in canada – buy doxycycline monohydrate

  28. ThomasInace说道:

    http://paxloviddelivery.pro/# paxlovid pharmacy

  29. kids cloths说道:

    The very next time I read a blog, I hope that it does not disappoint me as much as this particular one. After all, I know it was my choice to read through, however I really believed you would probably have something helpful to talk about. All I hear is a bunch of moaning about something that you could possibly fix if you weren’t too busy searching for attention.

  30. Jamesjer说道:

    buying generic clomid prices: how can i get generic clomid without insurance – generic clomid tablets

  31. Jamesjer说道:

    amoxicillin in india: amoxicillin pharmacy price – can we buy amoxcillin 500mg on ebay without prescription

  32. Jamesjer说道:

    cipro online no prescription in the usa: cipro ciprofloxacin – ciprofloxacin generic price

  33. Spot on with this write-up, I really believe that this website needs a lot more attention. I’ll probably be back again to read more, thanks for the information!

  34. Its like you read my mind You appear to know so much about this like you wrote the book in it or something I think that you can do with a few pics to drive the message home a little bit but instead of that this is excellent blog A fantastic read Ill certainly be back

  35. ThomasInace说道:

    http://amoxildelivery.pro/# amoxicillin 250 mg capsule

  36. kubet77说道:

    That is a very good tip especially to those new to the blogosphere. Brief but very precise information… Thanks for sharing this one. A must read article.

  37. Jamesjer说道:

    ciprofloxacin: buy ciprofloxacin over the counter – buy cipro online canada

  38. Hi! I could have sworn I’ve visited this web site before but after going through a few of the posts I realized it’s new to me. Regardless, I’m definitely happy I came across it and I’ll be book-marking it and checking back often.

  39. Jamesjer说道:

    buy ciprofloxacin: cipro ciprofloxacin – ciprofloxacin generic

  40. iptv说道:

    Pretty! This was a really wonderful article. Many thanks for providing this info.

  41. Jamesjer说道:

    can you get clomid without prescription: how can i get cheap clomid price – how can i get clomid

  42. ThomasInace说道:

    https://ciprodelivery.pro/# buy ciprofloxacin over the counter

发表回复

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