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

/ 324评论 / 1986阅读 / 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. Richardfrota说道:

    buy cheap neurontin online: neurontin 202 – generic neurontin cost

  2. Billyeroge说道:

    https://zithromaxa.store/# zithromax for sale 500 mg

  3. HenryIsona说道:

    where to purchase doxycycline: doxycycline monohydrate – 100mg doxycycline

  4. MarvinMek说道:

    zithromax online generic zithromax medicine zithromax prescription online

  5. HenryIsona说道:

    prescription prednisone cost: prednisone for sale – buy prednisone tablets uk

  6. HenryIsona说道:

    zithromax 600 mg tablets: zithromax 500 tablet – zithromax antibiotic

  7. CharlesGib说道:

    zithromax order online uk: zithromax 500 mg lowest price drugstore online – zithromax 500mg

  8. Richardfrota说道:

    online order prednisone: buy prednisone online from canada – where can i buy prednisone without a prescription

  9. Billyeroge说道:

    https://gabapentinneurontin.pro/# neurontin capsule 400 mg

  10. HenryIsona说道:

    zithromax over the counter uk: how to get zithromax online – zithromax online pharmacy canada

  11. MarvinMek说道:

    prednisone 2.5 tablet prednisone for dogs where can i buy prednisone online without a prescription

  12. Billyeroge说道:

    http://doxycyclinea.online/# doxycycline 100mg price

  13. Richardfrota说道:

    generic amoxil 500 mg: generic amoxil 500 mg – order amoxicillin online

  14. CharlesGib说道:

    prednisone without prescription.net: prednisone 50 mg price – 20 mg prednisone

  15. MarvinMek说道:

    amoxicillin generic amoxicillin online without prescription amoxicillin 500 mg purchase without prescription

  16. HenryIsona说道:

    80 mg prednisone daily: 50 mg prednisone tablet – where can you buy prednisone

  17. Felipelam说道:

    http://pharmworld.store/# drugstore com online pharmacy prescription drugs

  18. Donaldkenty说道:

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

  19. Williamfug说道:

    online pharmacy no prescription: pharm world – canadian pharmacy discount code

  20. DavidTaK说道:

    india pharmacy mail order india online pharmacy Online medicine order

  21. Jeromeviaph说道:

    https://pharmworld.store/# canadian pharmacies not requiring prescription

  22. DonaldtAg说道:

    reliable canadian pharmacy: ordering drugs from canada – canadian pharmacies that deliver to the us

  23. Felipelam说道:

    https://pharmnoprescription.icu/# best online pharmacy that does not require a prescription in india

  24. Williamfug说道:

    buy prescription drugs from india: Online medicine order – best india pharmacy

  25. Felipelam说道:

    https://pharmmexico.online/# п»їbest mexican online pharmacies

  26. Williamfug说道:

    mexico drug stores pharmacies: pharmacies in mexico that ship to usa – mexican border pharmacies shipping to usa

  27. DavidTaK说道:

    buy pain meds online without prescription online no prescription pharmacy pharmacy no prescription

  28. Felipelam说道:

    http://pharmworld.store/# no prescription needed pharmacy

  29. DonaldtAg说道:

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

  30. DavidTaK说道:

    indian pharmacies safe buy medicines online in india india pharmacy

  31. Williamfug说道:

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

  32. Donaldkenty说道:

    mexican mail order pharmacies: mexican rx online – buying prescription drugs in mexico online

  33. Felipelam说道:

    http://pharmworld.store/# canadian pharmacy no prescription

  34. Williamfug说道:

    canadian pharmacy no scripts: best canadian pharmacy online – canadian online drugs

  35. DonaldtAg说道:

    buy pain meds online without prescription: how to get a prescription in canada – buying prescription medications online

  36. DavidTaK说道:

    meds online without prescription no prescription medicine online pharmacy reviews no prescription

  37. Felipelam说道:

    https://pharmindia.online/# top online pharmacy india

  38. DavidBiolo说道:

    https://levitrav.store/# Levitra 10 mg best price

  39. Elmersoalf说道:

    buy Levitra over the counter buy Levitra over the counter Levitra 10 mg best price

  40. Charlesvox说道:

    http://levitrav.store/# п»їLevitra price

  41. Georgefrege说道:

    sildenafil over the counter: viagras.online – Cheapest Sildenafil online

  42. Jamesexite说道:

    Buy Vardenafil online: Cheap Levitra online – Levitra 20 mg for sale

  43. Elmersoalf说道:

    Kamagra Oral Jelly cheap kamagra п»їkamagra

  44. Charlesvox说道:

    http://levitrav.store/# Vardenafil online prescription

  45. Tylerreunk说道:

    https://viagras.online/# Order Viagra 50 mg online

  46. Jamesexite说道:

    Generic Cialis without a doctor prescription: Generic Tadalafil 20mg price – Cialis 20mg price

  47. Elmersoalf说道:

    Buy Levitra 20mg online Vardenafil online prescription Buy Levitra 20mg online

  48. Charlesvox说道:

    http://cenforce.pro/# cenforce.pro

  49. DavidBiolo说道:

    http://cialist.pro/# Generic Cialis price

  50. Jamesexite说道:

    Tadalafil price: Generic Cialis price – Generic Tadalafil 20mg price

回复 DavidTaK 取消回复

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