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

/ 4,990评论 / 17192阅读 / 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. Video Downloader说道:

    Every time I visit your website, I’m greeted with thought-provoking content and impeccable writing. You truly have a gift for articulating complex ideas in a clear and engaging manner.

  2. I also found the typical CTA trading a small minimum account size has concentrated portfolios, high-margin requirements, little money under management, a short track record, high volatility or was trading just options.

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

  4. In the United States before the financial crisis, the Federal Reserve used open market operations to keep its key policy rate, the federal funds rate, around the target set by the Federal Open Market Committee (FOMC) by adjusting the supply of reserve balances of commercial banks suitably.

  5. DarrelTrini说道:

    slot kumar siteleri: en iyi slot siteler – casino slot siteleri

  6. According to a survey done by Harris Interactive, 99 of the adults agreed that personal finance should be taught in schools.

  7. Or, at least, that’s the way it used to work.

  8. JesusDrems说道:

    deneme bonusu: bahis siteleri – bonus veren siteler

  9. KevinOvems说道:

    http://slotsiteleri.bid/# en iyi slot siteler

  10. JesusDrems说道:

    en yeni slot siteleri: oyun siteleri slot – guvenilir slot siteleri

  11. DarrelTrini说道:

    slot siteleri 2024: slot oyunlar? siteleri – deneme veren slot siteleri

  12. KevinOvems说道:

    http://slotsiteleri.bid/# slot bahis siteleri

  13. JesusDrems说道:

    sweet bonanza taktik: sweet bonanza kazanc – sweet bonanza taktik

  14. KevinOvems说道:

    https://slotsiteleri.bid/# en iyi slot siteleri

  15. JesusDrems说道:

    bonus veren siteler: bonus veren siteler – deneme bonusu veren siteler

  16. DarrelTrini说道:

    canl? slot siteleri: en guvenilir slot siteleri – en guvenilir slot siteleri

  17. DarrelTrini说道:

    en cok kazandiran slot siteleri: slot siteleri 2024 – guvenilir slot siteleri

  18. This blog was… how do you say it? Relevant!! Finally I have found something which helped me. Appreciate it.

  19. DarrelTrini说道:

    en iyi slot siteleri: yeni slot siteleri – en iyi slot siteleri

  20. JesusDrems说道:

    deneme bonusu veren siteler: bahis siteleri – deneme bonusu veren siteler

  21. JesusDrems说道:

    deneme bonusu: deneme bonusu – deneme bonusu

  22. HermanKak说道:

    canadian pharmacy 24: canadian online drugstore – canada pharmacy online

  23. JeremyRiz说道:

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

  24. Robertkaw说道:

    https://mexstarpharma.com/# mexican pharmaceuticals online

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

  26. JeremyRiz说道:

    https://mexstarpharma.com/# mexican online pharmacies prescription drugs

  27. PeterFum说道:

    canadian pharmacy world reviews: canadian drugs pharmacy – canadian pharmacy online reviews

  28. PeterFum说道:

    Online medicine home delivery: Online medicine home delivery – online pharmacy india

  29. Robertkaw说道:

    http://easyrxcanada.com/# pharmacy canadian

  30. Robertkaw说道:

    https://easyrxcanada.com/# my canadian pharmacy reviews

  31. PeterFum说道:

    indian pharmacy online: indian pharmacy online – Online medicine home delivery

  32. Robertkaw说道:

    https://easyrxindia.shop/# mail order pharmacy india

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

  34. PeterFum说道:

    northwest canadian pharmacy: onlinepharmaciescanada com – cross border pharmacy canada

  35. HermanKak说道:

    mexican pharmacy: medication from mexico pharmacy – mexican rx online

  36. HermanKak说道:

    top 10 online pharmacy in india: online shopping pharmacy india – indian pharmacy

  37. 33win说道:

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

  38. JeremyRiz说道:

    http://mexstarpharma.com/# п»їbest mexican online pharmacies

  39. JeremyRiz说道:

    http://mexstarpharma.com/# mexico pharmacies prescription drugs

  40. PeterFum说道:

    canadian pharmacy meds review: canadian pharmacy 24h com – canadian pharmacy antibiotics

  41. PeterFum说道:

    top online pharmacy india: buy medicines online in india – indian pharmacies safe

  42. Black Screen 65说道:

    I’m very pleased to uncover this web site. I want to to thank you for ones time just for this fantastic read!! I definitely liked every little bit of it and i also have you bookmarked to look at new stuff on your web site.

  43. PeterFum说道:

    mexican drugstore online: buying prescription drugs in mexico – mexico drug stores pharmacies

  44. Robertkaw说道:

    https://easyrxindia.shop/# Online medicine home delivery

  45. JeremyRiz说道:

    http://mexstarpharma.com/# mexican rx online

  46. JeremyRiz说道:

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

  47. PeterFum说道:

    indianpharmacy com: Online medicine home delivery – п»їlegitimate online pharmacies india

  48. link bokep说道:

    Howdy! This blog post could not be written much better! Looking at this post reminds me of my previous roommate! He always kept talking about this. I am going to forward this information to him. Fairly certain he’ll have a good read. Thanks for sharing!

  49. Robertkaw说道:

    http://mexstarpharma.com/# buying prescription drugs in mexico

  50. Robertkaw说道:

    https://easyrxcanada.online/# thecanadianpharmacy

发表回复

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