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

/ 4,984评论 / 17178阅读 / 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. Great post, I conceive people should learn a lot from this website its very user pleasant.

  2. Профессиональный сервисный центр по ремонту квадрокоптеров и радиоуправляемых дронов.
    Мы предлагаем:ремонт дронов москва
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  3. HermanKak说道:

    п»їlegitimate online pharmacies india: best india pharmacy – Online medicine home delivery

  4. Robertkaw说道:

    http://mexstarpharma.com/# mexican mail order pharmacies

  5. kontol说道:

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

  6. Профессиональный сервисный центр по ремонту сотовых телефонов, смартфонов и мобильных устройств.
    Мы предлагаем: ремонт мобильных телефонов
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  7. Excellent site. A lot of helpful information here. I am sending it to a few buddies ans also sharing in delicious. And naturally, thanks in your effort!

  8. Профессиональный сервисный центр по ремонту сотовых телефонов, смартфонов и мобильных устройств.
    Мы предлагаем: ближайший сервисный центр по ремонту телефонов
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  9. PeterFum说道:

    п»їbest mexican online pharmacies: reputable mexican pharmacies online – mexican border pharmacies shipping to usa

  10. PeterFum说道:

    purple pharmacy mexico price list: pharmacies in mexico that ship to usa – reputable mexican pharmacies online

  11. link bokep说道:

    Hello! I just would like to give you a huge thumbs up for your great information you have got here on this post. I am coming back to your web site for more soon.

  12. HermanKak说道:

    reputable indian pharmacies: online pharmacy india – indian pharmacies safe

  13. PeterFum说道:

    top online pharmacy india: Online medicine order – indian pharmacy

  14. HermanKak说道:

    purple pharmacy mexico price list: mexican drugstore online – pharmacies in mexico that ship to usa

  15. JeremyRiz说道:

    https://easyrxindia.shop/# best india pharmacy

  16. AnthonyFUS说道:

    top 10 pharmacies in india п»їlegitimate online pharmacies india indian pharmacies safe

  17. thefriskys说道:

    helloI really like your writing so a lot share we keep up a correspondence extra approximately your post on AOL I need an expert in this house to unravel my problem May be that is you Taking a look ahead to see you

  18. JeremyRiz说道:

    http://easyrxindia.com/# Online medicine order

  19. PeterFum说道:

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

  20. AnthonyFUS说道:

    vipps approved canadian online pharmacy adderall canadian pharmacy canadianpharmacymeds com

  21. Techno rozen说道:

    Techno rozen This is really interesting, You’re a very skilled blogger. I’ve joined your feed and look forward to seeking more of your magnificent post. Also, I’ve shared your site in my social networks!

  22. Inventory Trade trading actions additionally increased in 1988-1990 after the deregulation package in the banking and capital markets was launched.

  23. Clean everything completely and discard moldy materials.

  24. The CSS theory is only applicable in markets where share repurchases are allowed.

  25. He is best known for founding two high-frequency trading firms.

  26. If it doesn’t have the information it needs, it hands off the request downstream to other soft switches until it finds one that can answer the request.

  27. TK88说道:

    This website certainly has all of the information I needed concerning this subject and didn’t know who to ask.

  28. 五 の掲示说道:

    The term originates in 1961 with meteorologist Edward N. Lorenz and his fascination with how the smallest of atmospheric variables can result in drastically different weather models.

  29. Профессиональный сервисный центр по ремонту ноутбуков, макбуков и другой компьютерной техники.
    Мы предлагаем:профессиональный ремонт макбуков
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  30. AnthonyFUS说道:

    india pharmacy mail order indian pharmacy paypal reputable indian online pharmacy

  31. JeremyRiz说道:

    http://easyrxindia.com/# Online medicine home delivery

  32. Robertkaw说道:

    https://easyrxindia.shop/# top 10 online pharmacy in india

  33. PeterFum说道:

    medication from mexico pharmacy: reputable mexican pharmacies online – buying prescription drugs in mexico online

  34. Robertkaw说道:

    http://easyrxcanada.com/# canadian online drugstore

  35. porn说道:

    I’m amazed, I must say. Seldom do I encounter a blog that’s equally educative and entertaining, and let me tell you, you’ve hit the nail on the head. The issue is something too few men and women are speaking intelligently about. Now i’m very happy I found this in my search for something regarding this.

  36. Bé Cưng Store说道:

    Nice post. I learn something new and challenging on blogs I stumbleupon every day. It will always be interesting to read through articles from other writers and practice something from other web sites.

  37. Robertkaw说道:

    http://easyrxcanada.com/# canadian pharmacy uk delivery

  38. Mygreat learning说道:

    Mygreat learning You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!

  39. PeterFum说道:

    mail order pharmacy india: indian pharmacy online – india online pharmacy

  40. HermanKak说道:

    top online pharmacy india: india pharmacy – best online pharmacy india

  41. Nhà cái 789bet说道:

    Greetings! Very useful advice in this particular article! It’s the little changes that produce the most important changes. Many thanks for sharing!

  42. AnthonyFUS说道:

    reputable mexican pharmacies online mexico pharmacies prescription drugs mexico pharmacies prescription drugs

  43. AnthonyFUS说道:

    canadian family pharmacy canadian pharmacy meds reviews global pharmacy canada

  44. JeremyRiz说道:

    https://easyrxcanada.com/# canada pharmacy online

  45. JeremyRiz说道:

    https://easyrxindia.shop/# pharmacy website india

  46. AnthonyFUS说道:

    canadian pharmacy mall canadian pharmacy meds canadian pharmacy sarasota

  47. Robertkaw说道:

    http://mexstarpharma.com/# purple pharmacy mexico price list

  48. HermanKak说道:

    india pharmacy: indian pharmacy – cheapest online pharmacy india

  49. Robertkaw说道:

    http://mexstarpharma.com/# best online pharmacies in mexico

发表回复

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