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

/ 4,969评论 / 17146阅读 / 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. Douglasnug说道:

    india online pharmacy: Indian pharmacy international shipping – indian pharmacy paypal

  2. Douglasnug说道:

    pharmacies in mexico that ship to usa: mexico pharmacy win – mexico drug stores pharmacies

  3. notube mp3说道:

    An intriguing discussion is worth comment. I think that you should write more on this issue, it might not be a taboo subject but typically people do not speak about these subjects. To the next! Cheers.

  4. Leonardskarm说道:

    https://mexicopharmacy.win/# mexican online pharmacies prescription drugs

  5. wiresuk说道:

    Meu irmão sugeriu que eu pudesse gostar deste blog Ele estava totalmente certo Este post realmente fez o meu dia Você não pode imaginar quanto tempo gastei com esta informação Obrigado

  6. Leonardskarm说道:

    https://mexicopharmacy.win/# medication from mexico pharmacy

  7. Douglasnug说道:

    erectile dysfunction medicine online: ed pills online – buy erectile dysfunction pills

  8. Leonardskarm说道:

    http://mexicopharmacy.win/# buying from online mexican pharmacy

  9. Leonardskarm说道:

    https://mexicopharmacy.win/# mexican border pharmacies shipping to usa

  10. Douglasnug说道:

    reputable indian pharmacies: Indian pharmacy online – buy medicines online in india

  11. Douglasnug说道:

    indian pharmacy paypal: Online India pharmacy – Online medicine order

  12. Douglasnug说道:

    online pharmacy india: Top mail order pharmacies – india online pharmacy

  13. Leonardskarm说道:

    https://mexicopharmacy.win/# buying from online mexican pharmacy

  14. Leonardskarm说道:

    http://edpillpharmacy.store/# buy ed medication online

  15. Leonardskarm说道:

    https://edpillpharmacy.store/# low cost ed pills

  16. Leonardskarm说道:

    https://edpillpharmacy.store/# low cost ed medication

  17. Douglasnug说道:

    indian pharmacy paypal: Cheapest online pharmacy – reputable indian pharmacies

  18. Douglasnug说道:

    indianpharmacy com: Top online pharmacy in India – best india pharmacy

  19. Douglasnug说道:

    buy prescription drugs from india: Online pharmacy USA – indianpharmacy com

  20. Leonardskarm说道:

    https://mexicopharmacy.win/# medication from mexico pharmacy

  21. Leonardskarm说道:

    http://edpillpharmacy.store/# cheapest erectile dysfunction pills

  22. 韓国語 経済说道:

    The earlier questions – in particular, the ones that come just before a particular query – may provide information that subjects use as context in formulating their subsequent answers, or affect their thoughts, feelings and attitudes.

  23. Douglasnug说道:

    п»їlegitimate online pharmacies india: Indian pharmacy online – п»їlegitimate online pharmacies india

  24. Douglasnug说道:

    mexican online pharmacies prescription drugs: mexico pharmacy win – mexican pharmaceuticals online

  25. descargar musica说道:

    Very nice blog post. I definitely appreciate this website. Stick with it!

  26. 78win说道:

    Hi there! I just want to offer you a huge thumbs up for the great info you’ve got right here on this post. I will be coming back to your web site for more soon.

  27. Leonardskarm说道:

    https://indiapharmacy.shop/# online shopping pharmacy india

  28. Douglasnug说道:

    top 10 pharmacies in india: Online medicine home delivery – reputable indian online pharmacy

  29. Leonardskarm说道:

    https://edpillpharmacy.store/# erectile dysfunction pills online

  30. webech说道:

    Olá, boa postagem, há um problema com seu site no Internet Explorer, posso testar este IE, mas ainda é o líder do mercado e uma boa parte das pessoas ignorará sua escrita fantástica devido a esse problema

  31. Douglasnug说道:

    medicine in mexico pharmacies: Certified Mexican pharmacy – mexican mail order pharmacies

  32. Using a driver’s cellular phone as a data carrier, Entune connects with a host of concierge-like services from inside an Entune-equipped Toyota vehicle.

  33. 和泉市入札说道:

    Bacon (2002) proposed geometric excess return, as part of a geometric attribution, as a solution to this problem, and suggested that geometric attributions are preferable because they are compoundable, they are convertible among currencies, and they are proportionate (between different asset bases from period to period).

  34. 損 ことわざ说道:

    To get maximum mileage out of a corporate gift, it should bring the expected results to both the giver; in this case, you and the receiver: the client.

  35. Tenant Risk: The success of commercial real estate investments depends on securing and retaining tenants who pay rent on time and maintain the property.

  36. Douglasnug说道:

    buy medicines online in india: Online pharmacy USA – indian pharmacies safe

  37. Leonardskarm说道:

    http://mexicopharmacy.win/# medication from mexico pharmacy

  38. Leonardskarm说道:

    http://mexicopharmacy.win/# mexican pharmaceuticals online

  39. gay porn说道:

    homosexual porn

  40. Douglasnug说道:

    buy ed pills: Best ED meds online – best online ed medication

  41. Leonardskarm说道:

    https://indiapharmacy.shop/# world pharmacy india

  42. Leonardskarm说道:

    https://mexicopharmacy.win/# buying prescription drugs in mexico online

  43. Douglasnug说道:

    buy erectile dysfunction pills: buy ed pills online – cheap ed medication

  44. Good article. I will be experiencing many of these issues as well..

  45. Douglasnug说道:

    п»їlegitimate online pharmacies india: Indian pharmacy online – indianpharmacy com

发表回复

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