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

/ 4,888评论 / 16998阅读 / 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. Robertperma说道:

    buy misoprostol over the counter cytotec pills buy online cytotec buy online usa

  2. LewisToite说道:

    http://cytotecbestprice.pro/# buy cytotec pills online cheap

  3. PatrickHindy说道:

    http://cytotecbestprice.pro/# cytotec abortion pill

  4. Matthewnouts说道:

    buy zithromax: zithromax online no prescription – azithromycin zithromax

  5. Robertperma说道:

    how to get zithromax online zithromax order online uk how much is zithromax 250 mg

  6. LewisToite说道:

    https://prednisonebestprice.pro/# cheapest prednisone no prescription

  7. LewisToite说道:

    https://prednisonebestprice.pro/# prednisone cream rx

  8. PatrickHindy说道:

    https://nolvadexbestprice.pro/# does tamoxifen cause bone loss

  9. Matthewnouts说道:

    buy cytotec in usa: cytotec pills buy online – buy cytotec pills online cheap

  10. Robertperma说道:

    cytotec pills buy online buy cytotec online Cytotec 200mcg price

  11. PatrickHindy说道:

    http://zithromaxbestprice.pro/# cost of generic zithromax

  12. Matthewnouts说道:

    tamoxifen hair loss: tamoxifen hair loss – tamoxifen and weight loss

  13. Robertperma说道:

    where can i buy nolvadex nolvadex online tamoxifen and osteoporosis

  14. LewisToite说道:

    https://cytotecbestprice.pro/# cytotec abortion pill

  15. PatrickHindy说道:

    http://prednisonebestprice.pro/# 40 mg prednisone pill

  16. Matthewnouts说道:

    buy cytotec online: cytotec buy online usa – cytotec abortion pill

  17. Robertperma说道:

    zithromax 500 mg lowest price pharmacy online can you buy zithromax online where can i purchase zithromax online

  18. DominicHOr说道:

    mexican drugstore online: mexico pharmacies prescription drugs – mexican mail order pharmacies

  19. Waynetar说道:

    pharmacies in mexico that ship to usa: mexican border pharmacies shipping to usa – best online pharmacies in mexico

  20. NelsonSaIlk说道:

    buying from online mexican pharmacy: buying prescription drugs in mexico – buying prescription drugs in mexico

  21. Casino说道:

    Oh my goodness! Impressive article dude! Many thanks, However I am having problems with your RSS. I don’t understand the reason why I cannot subscribe to it. Is there anybody having identical RSS issues? Anyone that knows the solution will you kindly respond? Thanx!!

  22. Arnoldscava说道:

    mexican border pharmacies shipping to usa buying from online mexican pharmacy mexican rx online

  23. DominicHOr说道:

    medication from mexico pharmacy: mexican online pharmacies prescription drugs – mexican rx online

  24. Waynetar说道:

    medication from mexico pharmacy: mexican rx online – medicine in mexico pharmacies

  25. Waynetar说道:

    mexican rx online: mexican mail order pharmacies – mexican pharmaceuticals online

  26. NelsonSaIlk说道:

    medicine in mexico pharmacies: mexico drug stores pharmacies – purple pharmacy mexico price list

  27. Waynetar说道:

    medicine in mexico pharmacies: п»їbest mexican online pharmacies – mexican border pharmacies shipping to usa

  28. NelsonSaIlk说道:

    mexican rx online: mexico drug stores pharmacies – п»їbest mexican online pharmacies

  29. Arnoldscava说道:

    medication from mexico pharmacy best online pharmacies in mexico purple pharmacy mexico price list

  30. Arnoldscava说道:

    mexican pharmacy п»їbest mexican online pharmacies mexican drugstore online

  31. DominicHOr说道:

    buying prescription drugs in mexico: reputable mexican pharmacies online – mexican pharmaceuticals online

  32. NelsonSaIlk说道:

    mexican mail order pharmacies: buying from online mexican pharmacy – best online pharmacies in mexico

  33. DominicHOr说道:

    buying prescription drugs in mexico online: mexican rx online – reputable mexican pharmacies online

  34. Arnoldscava说道:

    best online pharmacies in mexico mexican mail order pharmacies purple pharmacy mexico price list

  35. DominicHOr说道:

    mexican online pharmacies prescription drugs: medication from mexico pharmacy – medicine in mexico pharmacies

  36. Waynetar说道:

    mexican mail order pharmacies: buying from online mexican pharmacy – pharmacies in mexico that ship to usa

  37. NelsonSaIlk说道:

    reputable mexican pharmacies online: best online pharmacies in mexico – mexico drug stores pharmacies

  38. go here说道:

    I love it when people come together and share thoughts. Great blog, stick with it.

  39. Arnoldscava说道:

    mexico pharmacies prescription drugs mexico drug stores pharmacies buying prescription drugs in mexico

  40. DominicHOr说道:

    mexican border pharmacies shipping to usa: mexican drugstore online – mexican mail order pharmacies

  41. Overall I attempt and ingest my mix of Vitamin C from pills. While I’d really like to via a excellent meal plan it can be rather strenous to at all times.

  42. Waynetar说道:

    buying from online mexican pharmacy: mexican online pharmacies prescription drugs – buying from online mexican pharmacy

  43. Waynetar说道:

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

  44. NelsonSaIlk说道:

    п»їbest mexican online pharmacies: buying from online mexican pharmacy – purple pharmacy mexico price list

  45. Waynetar说道:

    best online pharmacies in mexico: buying prescription drugs in mexico online – buying from online mexican pharmacy

  46. Arnoldscava说道:

    best online pharmacies in mexico mexican online pharmacies prescription drugs best online pharmacies in mexico

  47. DominicHOr说道:

    pharmacies in mexico that ship to usa: best online pharmacies in mexico – buying prescription drugs in mexico online

  48. DominicHOr说道:

    mexico pharmacies prescription drugs: best online pharmacies in mexico – buying prescription drugs in mexico online

  49. Arnoldscava说道:

    mexican online pharmacies prescription drugs mexican mail order pharmacies best online pharmacies in mexico

发表回复

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