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

/ 2,650评论 / 10593阅读 / 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. Wow, saya menemukan artikel ini di Google. Saya tertarik dan menandainya. Tentu saja saya juga sangat menyukai website Anda, sangat ringkas dan berisi banyak artikel dan informasi menarik.

  2. ThomasInace说道:

    https://doxycyclinedelivery.pro/# doxycycline hyclate 100 mg cap

  3. Jamesjer说道:

    amoxil generic: how to get amoxicillin over the counter – can i buy amoxicillin over the counter in australia

  4. iptv说道:

    bookmarked!!, I really like your website!

  5. skor real madrid说道:

    Saya menemukan situs Anda di Google secara tidak sengaja. Sangat keren dan bagi siapa pun yang benar-benar tertarik, blog ini luar biasa hasil skor real madrid

  6. ThomasInace说道:

    http://amoxildelivery.pro/# amoxicillin online purchase

  7. Jamesjer说道:

    doxycycline 20 mg: doxycycline order – doxycycline discount

  8. ThomasInace说道:

    http://clomiddelivery.pro/# can i get generic clomid without prescription

  9. iptv说道:

    Good day! I could have sworn I’ve been to this blog before but after going through many of the articles I realized it’s new to me. Regardless, I’m definitely delighted I stumbled upon it and I’ll be book-marking it and checking back often.

  10. ThomasInace说道:

    https://paxloviddelivery.pro/# paxlovid for sale

  11. Jamesjer说道:

    paxlovid for sale: Paxlovid buy online – paxlovid generic

  12. Jamesjer说道:

    paxlovid cost without insurance: Paxlovid over the counter – Paxlovid buy online

  13. I’m impressed, I must say. Seldom do I come across a blog that’s both equally educative and amusing, and without a doubt, you have hit the nail on the head. The issue is something too few people are speaking intelligently about. I am very happy I came across this in my hunt for something relating to this.

  14. Jamesjer说道:

    cipro pharmacy: buy cipro online – buy cipro online usa

  15. ThomasInace说道:

    https://amoxildelivery.pro/# where can you buy amoxicillin over the counter

  16. ThomasInace说道:

    https://ciprodelivery.pro/# ciprofloxacin 500 mg tablet price

  17. ngentot说道:

    May I simply say what a comfort to discover an individual who genuinely knows what they are talking about on the internet. You certainly know how to bring an issue to light and make it important. More and more people have to read this and understand this side of the story. I was surprised you are not more popular because you surely possess the gift.

  18. Jamesjer说道:

    where can i buy clomid: where can i get clomid prices – where to get generic clomid without rx

  19. ngentot pepek说道:

    I’m very pleased to uncover this page. I wanted to thank you for ones time for this fantastic read!! I definitely appreciated every bit of it and I have you saved to fav to look at new stuff on your website.

  20. ThomasInace说道:

    http://amoxildelivery.pro/# amoxicillin 500mg price canada

  21. Jamesjer说道:

    cheapest 40 mg doxycycline: buy doxycycline 100mg capsule – doxycycline tablets 100mg

  22. ThomasInace说道:

    https://ciprodelivery.pro/# ciprofloxacin over the counter

  23. Jamesjer说道:

    how to get doxycycline 100mg: purchase doxycycline – doxycycline 100mg capsules uk

  24. ThomasInace说道:

    http://ciprodelivery.pro/# ciprofloxacin generic price

  25. learp说道:

    He didn’t stop there, though. Charlie Munger went on to say that most cryptocurrencies aren’t just unprofitable, but he thinks bagholders will eventually lose all their money: This is the crypto offer cryptocurrency enthusiasts like you have been waiting for. Your wait is finally over. Outside of Nvidia, the biggest story in markets this year has been the comeback in crypto. Benjamin Godfrey is a blockchain enthusiast and journalists who relish writing about the real life applications of blockchain technology and innovations to drive general acceptance and worldwide integration of the emerging technology. His desires to educate people about cryptocurrencies inspires his contributions to renowned blockchain based media and sites. Benjamin Godfrey is a lover of sports and agriculture. Follow him on Twitter, Linkedin
    https://directoryreactor.com/listings12728137/website-under-review
    Email: contact@coinlore LONG CHARIZARD smart contract address is 0x4a9933c50dd83c5502da2bb8257910c631ef24ed. We are thrilled to announce that we will start the fair launch of the Charizard (CRZ), Proof-of-Burn (PoB) based meme coin. Collectibles, Mineral Rights & Crypto: Easy Ways to Conceal Assets Email: contact@coinlore Here at Arnold Jewelry & Coin, one or multiple of our coin buyers can make an appointment to come out to you and evaluate your collection. The initial cost for an evaluation is $60 hour and we can tell you individual values or pricing for the entire collection – if you end up selling the collection or part of the collection to our coin shop the hourly fee is waived. In addition to coins, we buy paper currency, cards, comics, antiques & other collector items.

  26. Jamesjer说道:

    cipro: buy ciprofloxacin over the counter – buy cipro online without prescription

  27. Pretty! This has been an extremely wonderful post. Thank you for supplying this info.

  28. youtube to mp3说道:

    Your blog is a breath of fresh air in the often mundane world of online content. Your unique perspective and engaging writing style never fail to leave a lasting impression. Thank you for sharing your insights with us.

  29. ThomasInace说道:

    http://paxloviddelivery.pro/# paxlovid generic

  30. ThomasInace说道:

    https://ciprodelivery.pro/# buy cipro cheap

  31. Jamesjer说道:

    amoxicillin 500 coupon: order amoxicillin online no prescription – amoxicillin pharmacy price

  32. services说道:

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

  33. Jamesjer说道:

    where buy clomid prices: how to buy generic clomid for sale – buy generic clomid no prescription

  34. ThomasInace说道:

    https://doxycyclinedelivery.pro/# doxycycline 100mg lowest price

  35. Jamesjer说道:

    drug doxycycline: where to buy doxycycline over the counter – doxycycline online for dogs

  36. ngentot说道:

    Pretty! This was an extremely wonderful post. Many thanks for providing this information.

  37. seo 백링크说道:

    I’m impressed by the depth of your analysis.구글SEO

  38. youtube to mp3说道:

    Your ability to distill complex concepts into digestible nuggets of wisdom is truly remarkable. I always come away from your blog feeling enlightened and inspired. Keep up the phenomenal work!

  39. ThomasInace说道:

    http://amoxildelivery.pro/# generic amoxil 500 mg

  40. ThomasInace说道:

    http://ciprodelivery.pro/# ciprofloxacin 500 mg tablet price

  41. sex说道:

    This blog was… how do I say it? Relevant!! Finally I have found something that helped me. Thanks.

  42. ThomasInace说道:

    http://ciprodelivery.pro/# buy cipro online without prescription

  43. DavidWaype说道:

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

发表回复

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