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

/ 4,959评论 / 17126阅读 / 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. Georgemuh说道:

    cialis brand no prescription 365: Buy Cialis online – i need cialis

  2. more info说道:

    Spot on with this write-up, I seriously believe that this website needs a lot more attention. I’ll probably be returning to read more, thanks for the info.

  3. Samuelrip说道:

    https://sildenafil.llc/# cialis vs viagra

  4. Samuelrip说道:

    https://tadalafil.auction/# cialis without a doctor prescription

  5. Tomasdrads说道:

    acquistare farmaci senza ricetta: avanafil generico – farmacia online

  6. Timothyomide说道:

    http://cialisgenerico.life/# farmacia online piГ№ conveniente

  7. Tomasdrads说道:

    dove acquistare viagra in modo sicuro: viagra senza ricetta – viagra generico recensioni

  8. RandyBulty说道:

    Farmacie online sicure: Avanafil 50 mg – acquistare farmaci senza ricetta

  9. Timothyomide说道:

    https://farmait.store/# Farmacie online sicure

  10. webcam girls说道:

    This blog was… how do I say it? Relevant!! Finally I have found something which helped me. Thanks a lot!

  11. Timothyomide说道:

    http://avanafil.pro/# Farmacie on line spedizione gratuita

  12. RandyBulty说道:

    viagra acquisto in contrassegno in italia: viagra generico sandoz – cerco viagra a buon prezzo

  13. Tomasdrads说道:

    farmacie online sicure: Tadalafil generico migliore – comprare farmaci online all’estero

  14. RandyBulty说道:

    Farmacia online piГ№ conveniente: Farmacia online piu conveniente – acquisto farmaci con ricetta

  15. ngentot pepek说道:

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

  16. Tomasdrads说道:

    comprare farmaci online con ricetta: Cialis generico controindicazioni – Farmacie online sicure

  17. Tomasdrads说道:

    farmacie online autorizzate elenco: Avanafil 50 mg – farmaci senza ricetta elenco

  18. Tomasdrads说道:

    farmacie online autorizzate elenco: Cialis generico recensioni – migliori farmacie online 2024

  19. RandyBulty说道:

    farmacia online senza ricetta: kamagra oral jelly – Farmacie on line spedizione gratuita

  20. Timothyomide说道:

    https://farmait.store/# top farmacia online

  21. RandyBulty说道:

    top farmacia online: Cialis generico prezzo – acquisto farmaci con ricetta

  22. Tomasdrads说道:

    Farmacie online sicure: Cialis generico 5 mg prezzo – Farmacie on line spedizione gratuita

  23. Tomasdrads说道:

    farmacie online sicure: Cialis generico farmacia – farmacia online senza ricetta

  24. Tomasdrads说道:

    viagra generico prezzo piГ№ basso: acquisto viagra – alternativa al viagra senza ricetta in farmacia

  25. NathanIdeft说道:

    Link pyramid, tier 1, tier 2, tier 3
    Tier 1 – 500 connections with placement embedded in pieces on writing portals

    Tier 2 – 3000 domain +Redirect links

    Level 3 – 20000 references combination, posts, posts

    Employing a link structure is helpful for indexing systems.

    Require:

    One link to the website.

    Search Terms.

    Accurate when 1 query term from the website topic.

    Highlight the extra service!

    Essential! First-level links do not overlap with Secondary and Tertiary-tier links

    A link structure is a instrument for boosting the movement and backlink portfolio of a internet domain or social network

  26. Timothyomide说道:

    http://farmait.store/# farmacie online affidabili

  27. RandyBulty说道:

    farmacie online autorizzate elenco: Avanafil prezzo – acquisto farmaci con ricetta

  28. Tomasdrads说道:

    farmacie online sicure: avanafil 100 mg prezzo – farmacia online

  29. Timothyomide说道:

    http://avanafil.pro/# farmacie online affidabili

  30. Bacará ao vivo说道:

    oi, gostei muito da sua escrita, compartilhe, entraremos em contato mais sobre seu artigo na AOL, preciso de um especialista nesta área para resolver meu problema Talvez seja você. Ansioso para vê-lo

  31. hellcase code说道:

    Hi, I do think this is a great blog. I stumbledupon it 😉 I’m going to revisit once again since I book-marked it. Money and freedom is the greatest way to change, may you be rich and continue to help others.

  32. RandyBulty说道:

    comprare farmaci online con ricetta: Farmacia online piu conveniente – Farmacia online miglior prezzo

  33. Tomasdrads说道:

    п»їFarmacia online migliore: kamagra – acquisto farmaci con ricetta

  34. Tomasdrads说道:

    farmacia online: Avanafil prezzo – Farmacie on line spedizione gratuita

  35. RandyBulty说道:

    farmacia online senza ricetta: farmacia online migliore – farmacie online autorizzate elenco

  36. Tomasdrads说道:

    farmacia online senza ricetta: kamagra gel – farmacie online affidabili

  37. Timothyomide说道:

    https://avanafil.pro/# farmacia online

  38. You made some first rate factors there. I appeared on the web for the issue and located most people will associate with with your website.

  39. RandyBulty说道:

    alternativa al viagra senza ricetta in farmacia: viagra senza prescrizione – cialis farmacia senza ricetta

  40. RandyBulty说道:

    п»їFarmacia online migliore: Cialis generico 20 mg 8 compresse prezzo – farmacia online piГ№ conveniente

  41. Whitescreen57说道:

    I want to to thank you for this fantastic read!! I definitely loved every little bit of it. I have got you saved as a favorite to check out new things you post…

  42. Tomasdrads说道:

    п»їFarmacia online migliore: kamagra – farmaci senza ricetta elenco

  43. RandyBulty说道:

    farmacia online senza ricetta: Farmacia online migliore – farmacie online affidabili

  44. Tomasdrads说道:

    п»їFarmacia online migliore: Cialis generico 20 mg 8 compresse prezzo – farmacie online affidabili

  45. Tomasdrads说道:

    viagra online in 2 giorni: viagra online siti sicuri – viagra online spedizione gratuita

  46. Timothyomide说道:

    https://cialisgenerico.life/# Farmacie on line spedizione gratuita

发表回复

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