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

/ 5,209评论 / 17761阅读 / 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. AlbertVed说道:

    buy Lisinopril 1st: Lisinopril 1st – lisinopril1st

  2. BernardGab说道:

    cytotec online cheapest cytotec buy cytotec online

  3. AlbertVed说道:

    Lisinopril 1st: Lisinopril 1st – cheapest Lisinopril

  4. DarrenDug说道:

    http://iverfast.com/# ivermectin humans

  5. Brandenven说道:

    buy dapoxetine online: cheap priligy – buy priligy

  6. Neon japonais说道:

    It’s difficult to find well-informed people in this particular subject, but you sound like you know what you’re talking about! Thanks

  7. Platte in 1944 and had 4 youngsters.

  8. The Susquehanna River reached a record excessive of 42.6 feet (13.0 meters) in Wilkes-Barre.

  9. Flagstaff is an space “of great ecological variation” on account of its numerous habitat life zones.

  10. A field truck was additionally thrown and destroyed, a part of which was discovered one hundred yards (91 m) away.

  11. The Sith are dedicated to the “Code of the Sith” and to mastering the darkish facet of the Pressure.

  12. 夏熱食べ物说道:

    The judge proclaimed that “it was their (the marketing campaign’s) lack of affordable diligence that in the end thwarted their effort to realize ballot access here” in West Virginia.

  13. Billboard charts comprehensive update incomplete.

  14. What Can the Rutherford County Juvenile Detention Heart Do For You?

  15. Wednesday in Washington Road Baptist Church with the Rev.

  16. The tornado weakened to EF1 strength as it crossed Van Meter Street and Fuqua Highway, however continued to cause intensive tree damage.

  17. Sometime after Victoria had parted company with the Physician on 20th century Earth (Fury from the Deep), she is lured back to the Detsen Monastery in Tibet (The Abominable Snowmen) by a dream telling her she’ll discover her late father there.

  18. sbi 資産说道:

    Strong Waste Administration – reusing, recycling and proper disposal of wastes are very important to keep our setting clean and to make our planet wholesome.

  19. Kathryn Hooker of Houston, Tex.

  20. Center East is a centre of many company occasions along with activities all through each season.

  21. From 1571 till 1885, it was a parliamentary borough, which returned two Member of Parliament (MPs) to the Home of Commons of the Parliament of the United Kingdom until 1868, and one member between 1868 and 1885.

  22. For earlier creators these intermediates (and there was usually a couple of) meant you need much bigger audiences to have a success.

  23. Lindsay, William R. Therapy of American Prisoners Throughout the Revolution.

  24. Opposite to my first impression while taking part in the game, Gunther just isn’t joking.

  25. A information to the geology of the Flagstaff area (PDF).

  26. Also find out how spanish there are, the more formal, the most half, for probably the most vocabulary there are and the extra study spanish for college students, spanish talking nation, be taught spanish for adults, learn spanish for kids, learn spanish for english audio system.

  27. Brandenven说道:

    priligy max pharm: cheap priligy – priligy max pharm

  28. hdhub4uin说道:

    hiI like your writing so much share we be in contact more approximately your article on AOL I need a specialist in this area to resolve my problem Maybe that is you Looking ahead to see you

  29. AlbertVed说道:

    buy cytotec pills: cytpremium – п»їcytotec pills online

  30. Узнай все о септопластика и вазотомия стоимость в москвесептопластика москва

  31. casino bet说道:

    Saved as a favorite, I love your site!

  32. BernardGab说道:

    stromectol tablets 3 mg iver fast ivermectin 6mg

  33. Brandenven说道:

    how to get cheap clomid price: clomid – where can i get generic clomid without rx

  34. xnxx.com说道:

    Hello there! This blog post could not be written any better! Looking through this article reminds me of my previous roommate! He continually kept preaching about this. I most certainly will send this information to him. Fairly certain he’ll have a very good read. Thanks for sharing!

  35. BernardGab说道:

    ivermectin buy Ivermectin online stromectol tablets for humans

  36. DarrenDug说道:

    http://lisinopril1st.com/# buy Lisinopril 1st

  37. Davidhax说道:

    п»їbest mexican online pharmacies http://mexicanpharmgate.com/ buying prescription drugs in mexico

  38. Brandenven说道:

    prednisone online australia: prednisone ray pharm – prednisone over the counter

  39. AlbertVed说道:

    Cytotec 200mcg price: buy cytotec cytpremium – cytotec abortion pill

  40. Узнай все о удаление полипа в матке гистероскопия цена москваудаление полипа в матке в москве

  41. Davidhax说道:

    medicine in mexico pharmacies https://mexicanpharmgate.com/ buying prescription drugs in mexico online

  42. DarrenDug说道:

    https://plavixclo.com/# plavix medication

  43. Davidhax说道:

    buying from online mexican pharmacy https://mexicanpharmgate.com/ mexican online pharmacies prescription drugs

  44. AlbertVed说道:

    lisinopril1st: lisinopril1st – buy Lisinopril 1st

  45. Brandenven说道:

    prednisone tabs 20 mg: prednisoneraypharm – canadian online pharmacy prednisone

  46. Brandenven说道:

    amoxicillin 500mg capsules: buy amoxil online – buy amoxicillin 500mg

发表回复

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