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

/ 4,972评论 / 17151阅读 / 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. JamesRok说道:

    zestril no prescription: Lisinopril refill online – zestril 40 mg

  2. JamesRok说道:

    lisinopril 20g: Lisinopril refill online – cheap lisinopril 40 mg

  3. Manifestation说道:

    I love reading through an article that will make people think. Also, thank you for allowing for me to comment.

  4. StephenJonge说道:

    http://lipitor.guru/# lipitor over the counter

  5. StanleyMaf说道:

    lasix furosemide online lasix 40mg

  6. StephenJonge说道:

    https://cytotec.pro/# buy cytotec

  7. StanleyMaf说道:

    generic lasix lasix generic lasix 100 mg tablet

  8. JamesRok说道:

    cytotec pills buy online: Misoprostol price in pharmacy – cytotec online

  9. StanleyMaf说道:

    buy cytotec over the counter Misoprostol price in pharmacy cytotec buy online usa

  10. StephenJonge说道:

    http://lisinopril.guru/# lisinopril 4214

  11. StephenJonge说道:

    http://lipitor.guru/# buy lipitor online

  12. DanielDrync说道:

    buy misoprostol over the counter https://lisinopril.guru/# lisinopril online without prescription
    lasix medication

  13. uwhuutxhv说道:

    This page is not available. Return to Home Page Belka, is back. Still a belter… Anastasia Brokelyn has returned from the beach with only her bikini and flimsy top. She doesn’t seem to unhappy about it, however… RULES – Students Playing Strip Poker, Things Get Crazy! Yo! Calling all strip poker fans out there! Want to have some fun with international poker players and see them strip for your pleasure? Check out My Strip Poker today and have yourself some fun! Your email address will not be published. Required fields are marked * Tawnee Stone and Dirty ali strip poker FIST4K. Stud fists GFs pussy after they play strip poker in kitchen This website contains age-restricted materials including nudity and explicit depictions of sexual activity. By entering, you affirm that you are at least 18 years of age or the age of majority in the jurisdiction you are accessing the website from and you consent to viewing sexually explicit content.
    https://jaspervogn854119.aboutyoublog.com/28295968/baccarat-game-news
    At Wild Joker Online Casino, we are not only generous with our free spins and bonuses on our great online pokies, but we also provide the best online casino welcome offer you won’t find anywhere else. Take this WILD welcome offer now: A valuable diamond in 3 places on the middle reels pays 1x the stake, and then awards a spin on wheel of fortune. The 10 segments of the wheel hold from 10 free spins with a 2x multiplier on all wins, to 30 free games where all wins are tripled. Multipliers don’t apply to Joker wins though. You can retrigger the free games with 3 more scatter symbols on any spin. There are currently no known player issues pertaining to how Wild Joker Casino conducts their gaming operations. Founded in the U.S. state of Georgia in 1998, RealTime Gaming represents decades of experience. RTG is right at the top with industry leaders like Microgaming and NetEnt, providing games from their diverse library to dozens of online casinos, Wild Joker Casino included.

  14. DanielDrync说道:

    buy cytotec over the counter https://tamoxifen.bid/# tamoxifen pill
    lasix 20 mg

  15. JamesRok说道:

    generic lasix: furosemide online – buy lasix online

  16. JamesRok说道:

    lasix: furosemide online – furosemide 100 mg

  17. StanleyMaf说道:

    lisinopril pill 10mg cheap lisinopril how to buy lisinopril online

  18. DanielDrync说道:

    order cytotec online http://furosemide.win/# lasix 100 mg
    furosemide 100mg

  19. Hello there, I do believe your web site could possibly be having internet browser compatibility problems. Whenever I look at your site in Safari, it looks fine however, when opening in IE, it has some overlapping issues. I just wanted to provide you with a quick heads up! Apart from that, wonderful website!

  20. StanleyMaf说道:

    nolvadex d buy tamoxifen online nolvadex vs clomid

  21. JamesRok说道:

    lipitor 10 mg cost: Atorvastatin 20 mg buy online – buy lipitor cheap

  22. StanleyMaf说道:

    cytotec buy online usa buy cytotec in usa buy cytotec over the counter

  23. DanielDrync说道:

    buy cytotec over the counter https://tamoxifen.bid/# raloxifene vs tamoxifen
    lasix furosemide 40 mg

  24. StephenJonge说道:

    https://lipitor.guru/# lowest price lipitor

  25. StanleyMaf说道:

    buy cytotec pills online cheap cheapest cytotec buy cytotec online fast delivery

  26. StephenJonge说道:

    https://lipitor.guru/# lipitor 4 mg

  27. Discounted items说道:

    Way cool! Some extremely valid points! I appreciate you writing this article and the rest of the website is really good.

  28. Temp Mail说道:

    I was just as enthralled by your work as you were. The visual presentation is refined, and the written content is sophisticated. However, you seem anxious about the possibility of presenting something that could be perceived as questionable. I believe you’ll be able to rectify this matter in a timely manner.

  29. win79说道:

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

  30. rikvip说道:

    Nice post. I learn something new and challenging on websites I stumbleupon on a daily basis. It will always be interesting to read through articles from other writers and practice something from their websites.

  31. I always was interested in this topic and still am, regards for putting up.

  32. I used to be able to find good information from your content.

  33. ndgggvzcy说道:

    Board game box pricing increases with the dimensions of the box, meaning it’s uneconomical to choose a large box for a game with few pieces. Most industry leaders recommend against using a big box for a game with few components. Thanks for sharing this blog. The story your telling about how to make a classic board game box. The detail was outstanding and up to the mark. I pin this website for more interesting articles in future. And this could help me to make my Vape Cartridge Boxes like this one. We make our magnetic closure rigid boxes in the same high-quality materials as telescope boxes and with the same comprehensive range of options for covering, printing, and special finishes. The key difference is that these boxes have hinged lids or a folding design and they’re closed with a powerful magnetic catch. Ideal as a luxury-level stretch goal for your Kickstarter campaign or simply as a high-end solution to your game boxing needs. As with all our boxes, you can also insert a cardboard or plastic tray to house the game pieces or fill them with cut-out foam inserts for a very professional look.
    https://rowanxvab963319.blog2freedom.com/28650916/math-matching-games
    Setup recurring reminders by selecting tournament options like team size and game mode. Once a tournament is about to start, we will send you a push notification! In Rocket League, each team may have a maximum of six (6) players, broken down into three (3) starting players on the Roster, and three (3) substitutes on the Bench. No individual may simultaneously hold two or more roles as listed above. All players and coaches are expected to be present physically or virtually for all official PlayVS matches. Both the Roster and Bench must be finalized prior to the Roster Lock Date. The client will automatically generate a 32-team, single elimination bracket event, and upon reaching both Semifinals and Finals, players will play in a best of three match format. At first, Competitive Tournaments will be 3v3 that supports parties of all sizes, so a squad of three friends will face off against a solo-queued group. In this case, it might be a good idea to form up with some friends and communicate for a more coordinated approach, something that is not necessary in casual play, but probably an important component of competitive matches.

  34. Tooft说道:

    HEX price is $0.001603, up 9.78% in the last 24 hours, and the live market cap is $0. It has circulating supply of 0 HEX coins and a max supply of 598,857,169,162 HEX alongside $236,610 24h trading volume. The choice of colors for the Bitcoin brand is deliberate. The orange color is associated with energy, excitement, and innovation. The gray color is associated with trust, security, and stability. The white color is associated with purity, simplicity, and clarity. HEX uses the Ethereum network for the transaction layer (sending and receiving HEX tokens, as well as interacting with the HEX smart contract), whilst the consensus code and staking mechanism is contained in the HEX smart contract. The potential approval of a spot Bitcoin ETF in the US would provide enhanced trust and mainstream recognition for Bitcoin and the broader cryptocurrency market. ETFs are well-established investment vehicles that are widely recognized and understood by investors. The launch of a spot Bitcoin ETF in the US would introduce a regulated and familiar way for traditional investors to gain exposure to Bitcoin, potentially attracting a wider range of participants, increasing overall market confidence, and leading to the launch of other crypto ETFs.
    http://tmenter.net/bbs/board.php?bo_table=free&me_code=&wr_id=43966
    Narrator: In the horse-breeding world, genetics is king. Wealthy investors are willing to pay high prices for proven winners’ semen, hoping that the resulting foal provides a large return on investment. ICO Price (USD) Market depth is a metric, which is showing the real liquidity of the markets. Due to rampant wash-trading and fake activity – volume currently isn’t the most reliable indicator in the crypto space. With so much money to be made in racing, show jumping, dressage, and more, the price of horse semen will remain stable. CUM alıp saklamak için bir kripto para borsasında veya P2P pazar aracılığıyla satın alma işlemi yapabilirsiniz. CUM aldıktan sonra bunu bir kripto cüzdanda güvenli olarak saklamanız önemlidir, bu cüzdanlar da iki türlüdür: sıcak cüzdanlar (yazılım tabanlı, fiziksel cihazlarınızda saklanır) ve soğuk cüzdanlar (donanım tabanlı, çevrimdışı olarak saklanır).

  35. You’re so interesting! I do not think I’ve read through something like this before. So wonderful to find someone with genuine thoughts on this subject. Really.. thank you for starting this up. This web site is one thing that’s needed on the web, someone with a little originality.

  36. mpox pandemic说道:

    You have made some decent points there. I checked on the internet for more info about the issue and found most individuals will go along with your views on this site.

  37. K8说道:

    Way cool! Some extremely valid points! I appreciate you penning this write-up plus the rest of the site is also really good.

  38. Douglasnug说道:

    indian pharmacy paypal: Indian pharmacy online – world pharmacy india

  39. Douglasnug说道:

    pharmacies in mexico that ship to usa: mexican pharmacy – medication from mexico pharmacy

  40. Douglasnug说道:

    cheapest online pharmacy india: top 10 online pharmacy in india – mail order pharmacy india

  41. onbet说道:

    Way cool! Some very valid points! I appreciate you penning this post and the rest of the site is also really good.

  42. XO88说道:

    bookmarked!!, I really like your site.

  43. Douglasnug说道:

    buy medicines online in india: Online medicine home delivery – world pharmacy india

  44. Douglasnug说道:

    ed pills for sale: ed pills online – cheap erection pills

  45. Douglasnug说道:

    buy medicines online in india: top 10 pharmacies in india – pharmacy website india

  46. Douglasnug说道:

    indian pharmacies safe: Indian pharmacy international shipping – cheapest online pharmacy india

  47. myflixer说道:

    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.

  48. Douglasnug说道:

    indianpharmacy com: Online medicine home delivery – buy prescription drugs from india

  49. Douglasnug说道:

    ed rx online: Best ED pills non prescription – erectile dysfunction online

发表回复

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