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

/ 4,885评论 / 16992阅读 / 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. bestiptv1说道:

    I was pretty pleased to uncover this web site. I want to to thank you for ones time for this particularly fantastic read!! I definitely really liked every bit of it and I have you bookmarked to check out new stuff in your blog.

  2. I’m pretty pleased to discover this website. I want to to thank you for your time for this wonderful read!! I definitely really liked every little bit of it and I have you saved to fav to see new information in your website.

  3. video numerology说道:

    An impressive share! I have just forwarded this onto a friend who has been conducting a little homework on this. And he in fact ordered me lunch simply because I found it for him… lol. So allow me to reword this…. Thanks for the meal!! But yeah, thanks for spending time to talk about this issue here on your website.

  4. Slot terpercaya说道:

    Having read this I thought it was extremely enlightening. I appreciate you spending some time and energy to put this content together. I once again find myself spending a lot of time both reading and commenting. But so what, it was still worthwhile!

  5. Java Burn Review说道:

    Thank you for some other great post. The place else may anyone get that type of info in such a perfect manner of writing? I have a presentation next week, and I am on the look for such information.

  6. FitSpresso说道:

    It’s actually a great and helpful piece of information. I am happy that you just shared this useful information with us. Please stay us informed like this. Thanks for sharing.

  7. bokep ngentot说道:

    I need to to thank you for this good read!! I absolutely enjoyed every bit of it. I have you bookmarked to look at new stuff you post…

  8. ngentot memek说道:

    Very good info. Lucky me I recently found your blog by chance (stumbleupon). I have book-marked it for later.

  9. bokep ngentot说道:

    bookmarked!!, I like your site.

  10. dagathomonetcom说道:

    Hi there, I do believe your blog may be having browser compatibility problems. When I take a look at your blog in Safari, it looks fine but when opening in I.E., it has some overlapping issues. I just wanted to provide you with a quick heads up! Other than that, wonderful website.

  11. mp3 juice说道:

    Greetings! Very helpful advice within this article! It is the little changes that will make the biggest changes. Many thanks for sharing!

  12. Tonic Greens说道:

    You have brought up a very superb points, thanks for the post.

  13. Next time I read a blog, Hopefully it won’t disappoint me just as much as this one. I mean, Yes, it was my choice to read, nonetheless I truly thought you’d have something helpful to say. All I hear is a bunch of complaining about something you could fix if you weren’t too busy searching for attention.

  14. I seriously love your site.. Very nice colors & theme. Did you create this site yourself? Please reply back as I’m hoping to create my own personal site and want to find out where you got this from or what the theme is named. Thanks!

  15. Nice post. I find out something much harder on different blogs everyday. Most commonly it is stimulating to read content using their company writers and use something from their site. I’d want to use some while using content on my own blog no matter whether you do not mind. Natually I’ll offer you a link in your web weblog. Thank you sharing.

  16. I do believe you will find there’s problem with your site making use of Internet explorer browser.

  17. Genial der Artikel ist wirklich gut mach weiter so Viele Grüsse Saloma

  18. aphid control说道:

    I believe you have remarked some very interesting details , thankyou for the post.

  19. porn说道:

    Saved as a favorite, I like your website!

  20. I believe there’s a issue with your blog working with Safari internet browser.

  21. reast说道:

    Anecdotally, I’ve spoken to many mothers who have told me stories about the pleasures of playing video games with their children. For example, at one recent birthday party, a mother proudly told me how she, plays Clash of Clans with her sons, and that her parents have even gotten in on the game; three generations, all playing together. Follow us on social media to stay up to date on everything we’re doing. Game Mess Mornings 06 05 24 If you want to show your mother how much you love her, buy her a video game this Mother’s Day. Mother’s Day Trivia: Test your knowledge of all things Mother’s Day in this themed trivia game that promises fun for everyone. Mother’s Day games ideas to make the most of one of the biggest holidays in the calendar in terms of consumer spending. In the US it’s the third highest spending holiday, only behind Christmas and Valentine’s, and in the UK Mother’s Day generates close to £2 billion in consumer spending.
    https://mariolhcw406308.blogpayz.com/27490302/google-games-t-rex
    While Checkers is not quite as popular as a game like Chess, there is still a lot of strategy involved. Not to worry though, there are a few key strategies that you can use to win some games. GameTable is an interactive game company that offers an online checkers game. In this simple game, you can choose a one or two-player version. In either option, you can select themes, the board size, forced jumps available, and to show your moves. In the single-player, you can also choose from easy to expert. Once play begins, you have the option to get hints and reverse moves. This site also features a how-to-play section, history, and rules. © 2018 CoolGames All Rights Reserved It is recommended to follow the following instructions; in order to play checkers game and win in a professional way they are

  22. I am curious to find out what blog system you happen to be using? I’m experiencing some minor security problems with my latest website and I’d like to find something more safe. Do you have any suggestions?

  23. Balmorex说道:

    Glad to be one of the visitors on this awesome site : D.

  24. I dugg some of you post as I cerebrated they were very beneficial handy

  25. ant problem说道:

    Appreciate it to get a incredibly apparent and very helpful publish. I’m positively a violator of many of these rules. I generally uncover personally conflicted when producing a blog posting because I see myself personally creating more than people prefer to read, but I feel that I have got to do the subject matter proper rights by completely protecting it. I think that by pursuing some of these policies I finish up cutting out critical factors to the dialogue. I guess you could have to acquire a stability.

  26. spider control说道:

    Sewing Machines… […]plenty of time to read through as well as visit the articles as well as sites we have now linked to[…]…

  27. Casino说道:

    Aw, this was a very good post. Taking a few minutes and actual effort to generate a great article… but what can I say… I put things off a whole lot and never manage to get anything done.

  28. newsreality说道:

    I have read some excellent stuff here Definitely value bookmarking for revisiting I wonder how much effort you put to make the sort of excellent informative website

  29. jambiprov.go.id说道:

    Next time I read a blog, Hopefully it won’t fail me just as much as this particular one. I mean, I know it was my choice to read, nonetheless I really believed you would have something useful to talk about. All I hear is a bunch of complaining about something you could fix if you weren’t too busy searching for attention.

  30. MichaelLit说道:

    buying prescription drugs in mexico
    https://cmqpharma.com/# mexican drugstore online
    п»їbest mexican online pharmacies

  31. HenryGainc说道:

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

  32. hackers for hire说道:

    Hello! I just would like to give a huge thumbs up for the great info you have here on this post. I will be coming back to your blog for more soon.

  33. 주부 대출说道:

    This is exactly what I needed to read today.대출 갈아타기

  34. 귀하의 웹사이트에 이러한 귀중한 정보를 제공해 주셔서 감사합니다. 나는 그것들이 매우 유용하다는 것을 알았고 더 많은 것을 배우기 위해 확실히 돌아올 것입니다.

  35. I’m sharing this with my community.프리랜서 대출

  36. berita aceh说道:

    Very good article. I definitely love this website. Continue the good work!

  37. porn说道:

    This web site certainly has all the info I wanted about this subject and didn’t know who to ask.

  38. tubidy mp3说道:

    This site was… how do you say it? Relevant!! Finally I have found something which helped me. Thank you.

  39. This is the perfect web site for anybody who would like to understand this topic. You understand so much its almost tough to argue with you (not that I actually will need to…HaHa). You definitely put a fresh spin on a subject that’s been written about for decades. Great stuff, just excellent.

发表回复

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