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

/ 2,723评论 / 11087阅读 / 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. NelsonSaIlk说道:

    mexican mail order pharmacies: mexican border pharmacies shipping to usa – mexico pharmacies prescription drugs

  2. Arnoldscava说道:

    mexican border pharmacies shipping to usa mexican drugstore online pharmacies in mexico that ship to usa

  3. Waynetar说道:

    mexican mail order pharmacies: medicine in mexico pharmacies – pharmacies in mexico that ship to usa

  4. DominicHOr说道:

    mexican online pharmacies prescription drugs: reputable mexican pharmacies online – mexican mail order pharmacies

  5. NelsonSaIlk说道:

    п»їbest mexican online pharmacies: mexican drugstore online – medication from mexico pharmacy

  6. Waynetar说道:

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

  7. Arnoldscava说道:

    mexican drugstore online mexico drug stores pharmacies mexico pharmacy

  8. DominicHOr说道:

    pharmacies in mexico that ship to usa: mexico drug stores pharmacies – buying from online mexican pharmacy

  9. Arnoldscava说道:

    purple pharmacy mexico price list medicine in mexico pharmacies best online pharmacies in mexico

  10. Waynetar说道:

    mexican drugstore online: mexican mail order pharmacies – mexican drugstore online

  11. DominicHOr说道:

    mexican mail order pharmacies: mexican online pharmacies prescription drugs – medicine in mexico pharmacies

  12. casino说道:

    porn cannibalism

  13. Arnoldscava说道:

    mexican rx online mexican border pharmacies shipping to usa medicine in mexico pharmacies

  14. Waynetar说道:

    buying prescription drugs in mexico online: mexico drug stores pharmacies – п»їbest mexican online pharmacies

  15. DominicHOr说道:

    mexican border pharmacies shipping to usa: buying prescription drugs in mexico – mexico drug stores pharmacies

  16. NelsonSaIlk说道:

    mexican mail order pharmacies: medication from mexico pharmacy – buying prescription drugs in mexico

  17. NelsonSaIlk说道:

    mexico pharmacies prescription drugs: purple pharmacy mexico price list – mexican online pharmacies prescription drugs

  18. NelsonSaIlk说道:

    mexico pharmacies prescription drugs: medication from mexico pharmacy – purple pharmacy mexico price list

  19. Your blog is a beacon of light in the often murky waters of online content. Your thoughtful analysis and insightful commentary never fail to leave a lasting impression. Keep up the amazing work!

  20. Hello my loved one I want to say that this post is amazing great written and include almost all significant infos I would like to look extra posts like this

  21. Arnoldscava说道:

    mexico drug stores pharmacies mexican drugstore online buying from online mexican pharmacy

  22. Waynetar说道:

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

  23. DominicHOr说道:

    mexican rx online: purple pharmacy mexico price list – mexico drug stores pharmacies

  24. Thanks I have just been looking for information about this subject for a long time and yours is the best Ive discovered till now However what in regards to the bottom line Are you certain in regards to the supply

  25. Your blog is a true hidden gem on the internet. Your thoughtful analysis and engaging writing style set you apart from the crowd. Keep up the excellent work!

  26. What i do not realize is in fact how you are no longer actually much more wellfavored than you might be right now Youre very intelligent You recognize thus considerably in relation to this topic made me in my view believe it from numerous numerous angles Its like men and women are not fascinated until it is one thing to do with Lady gaga Your own stuffs excellent All the time handle it up

  27. Video Bokeh说道:

    Nice blog here Also your site loads up very fast What host are you using Can I get your affiliate link to your host I wish my site loaded up as quickly as yours lol

  28. NelsonSaIlk说道:

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

  29. Video Bokeh说道:

    Somebody essentially lend a hand to make significantly articles Id state That is the very first time I frequented your website page and up to now I surprised with the research you made to make this actual submit amazing Wonderful task

  30. Waynetar说道:

    buying prescription drugs in mexico online: mexico drug stores pharmacies – medicine in mexico pharmacies

  31. I was recommended this website by my cousin I am not sure whether this post is written by him as nobody else know such detailed about my difficulty You are wonderful Thanks

  32. DominicHOr说道:

    medicine in mexico pharmacies: mexican online pharmacies prescription drugs – mexico pharmacies prescription drugs

  33. Arnoldscava说道:

    reputable mexican pharmacies online medicine in mexico pharmacies reputable mexican pharmacies online

  34. Arnoldscava说道:

    п»їbest mexican online pharmacies medication from mexico pharmacy medication from mexico pharmacy

  35. Waynetar说道:

    best online pharmacies in mexico: mexican mail order pharmacies – mexican mail order pharmacies

  36. Xnxubd说道:

    Your blog is a constant source of inspiration for me. Your passion for your subject matter is palpable, and it’s clear that you pour your heart and soul into every post. Keep up the incredible work!

  37. Hi my loved one I wish to say that this post is amazing nice written and include approximately all vital infos Id like to peer more posts like this

  38. Arnoldscava说道:

    mexico drug stores pharmacies medication from mexico pharmacy reputable mexican pharmacies online

  39. Waynetar说道:

    medication from mexico pharmacy: mexican pharmaceuticals online – reputable mexican pharmacies online

  40. bokeh no blur说道:

    Usually I do not read article on blogs however I would like to say that this writeup very compelled me to take a look at and do so Your writing taste has been amazed me Thanks quite nice post

  41. bokeh no blur说道:

    Your writing has a way of resonating with me on a deep level. I appreciate the honesty and authenticity you bring to every post. Thank you for sharing your journey with us.

  42. DominicHOr说道:

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

  43. NelsonSaIlk说道:

    buying from online mexican pharmacy: purple pharmacy mexico price list – mexican pharmaceuticals online

  44. Fantastic site A lot of helpful info here Im sending it to some buddies ans additionally sharing in delicious And naturally thanks on your sweat

  45. NelsonSaIlk说道:

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

  46. Amie Emmerich说道:

    Your blog is a testament to your dedication to your craft. Your commitment to excellence is evident in every aspect of your writing. Thank you for being such a positive influence in the online community.

  47. NelsonSaIlk说道:

    buying prescription drugs in mexico: mexican border pharmacies shipping to usa – medicine in mexico pharmacies

  48. Arnoldscava说道:

    medicine in mexico pharmacies mexico drug stores pharmacies mexico pharmacies prescription drugs

  49. Waynetar说道:

    mexican drugstore online: buying prescription drugs in mexico – medicine in mexico pharmacies

发表回复

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