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

/ 4,962评论 / 17134阅读 / 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. CharlesLem说道:

    http://indiapharmacy.shop/# india pharmacy
    how to get ed meds online

  2. CharlesLem说道:

    http://indiapharmacy.shop/# mail order pharmacy india
    ed pills for sale

  3. Douglasnug说道:

    mexican drugstore online: mexican pharmacy – mexican drugstore online

  4. CharlesLem说道:

    https://mexicopharmacy.win/# buying prescription drugs in mexico
    ed treatment online

  5. Right here is the right web site for anybody who really wants to understand this topic. You know a whole lot its almost tough to argue with you (not that I actually will need to…HaHa). You definitely put a fresh spin on a topic that has been written about for decades. Wonderful stuff, just great.

  6. Douglasnug说道:

    ed treatments online: cheap ed pills online – cheap boner pills

  7. Leonardskarm说道:

    http://indiapharmacy.shop/# india pharmacy

  8. Douglasnug说道:

    cheap ed medicine: Cheapest online ED treatment – erectile dysfunction medication online

  9. CharlesLem说道:

    http://indiapharmacy.shop/# indianpharmacy com
    get ed prescription online

  10. CharlesLem说道:

    https://edpillpharmacy.store/# where can i buy ed pills
    discount ed meds

  11. CharlesLem说道:

    http://mexicopharmacy.win/# mexico drug stores pharmacies
    erection pills online

  12. Leonardskarm说道:

    http://mexicopharmacy.win/# best online pharmacies in mexico

  13. CharlesLem说道:

    http://edpillpharmacy.store/# where can i buy ed pills
    online erectile dysfunction pills

  14. Douglasnug说道:

    mexico pharmacies prescription drugs: mexico pharmacy win – mexico drug stores pharmacies

  15. Douglasnug说道:

    erectile dysfunction medicine online: ed pills online – generic ed meds online

  16. Douglasnug说道:

    п»їed pills online: ed pills online – boner pills online

  17. CharlesLem说道:

    https://mexicopharmacy.win/# buying prescription drugs in mexico
    erection pills online

  18. CharlesLem说道:

    http://mexicopharmacy.win/# mexican pharmaceuticals online
    cheap ed meds online

  19. Leonardskarm说道:

    http://indiapharmacy.shop/# india online pharmacy

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

  21. Georgemuh说道:

    generic cialisw: cheapest tadalafil – ed. trusted medstore in cialis

  22. Samuelrip说道:

    http://sildenafil.llc/# viagra side effects

  23. Samuelrip说道:

    https://tadalafil.auction/# cheapest cialis from india

  24. discover here说道:

    You have made some really good points there. I looked on the net for additional information about the issue and found most individuals will go along with your views on this web site.

  25. Georgemuh说道:

    buy viagra online without a prescription: Cheap generic Viagra – buy viagra online

  26. Georgemuh说道:

    cheapest cialis on the web: Generic Tadalafil 20mg price – shopping for cialis

  27. Samuelrip说道:

    http://tadalafil.auction/# cialis ordering australia

  28. Georgemuh说道:

    cialis 20mg online: cheapest tadalafil – cialis without a prescription paypal

  29. Normalmente eu não leio artigos em blogs, mas gostaria de dizer que este artigo me forçou a tentar fazê-lo. Seu estilo de escrita me surpreendeu. Obrigado, ótima postagem

  30. Georgemuh说道:

    order cialis online cheap generic: Buy Tadalafil 20mg – buy black cialis

  31. Excellent web site. Lots of useful information here. I am sending it to a few friends ans also sharing in delicious. And obviously, thanks for your sweat!

  32. tubidy download说道:

    You ought to be a part of a contest for one of the greatest blogs online. I’m going to highly recommend this website!

  33. Georgemuh说道:

    viagra samples: Buy Viagra online in USA – online viagra

  34. Georgemuh说道:

    viagra from canada: Buy Viagra online cheap – buy generic viagra online

  35. Samuelrip说道:

    https://tadalafil.auction/# cialis orders paypal paid

  36. Georgemuh说道:

    real viagra without a doctor prescription: Viagra online price – viagra without a doctor prescription

  37. Samuelrip说道:

    http://tadalafil.auction/# generic cialis uk online

  38. Georgemuh说道:

    buy cialis cheap fast delivery: Generic Cialis without a doctor prescription – cialis and no prescription

  39. sunwin说道:

    Spot on with this write-up, I honestly believe that this website needs far more attention. I’ll probably be back again to read through more, thanks for the information.

  40. Samuelrip说道:

    http://sildenafil.llc/# viagra without a doctor prescription usa

  41. Georgemuh说道:

    cialis sales canadian: Buy Cialis online – cheap online cialis

  42. Fake mail说道:

    Your posts always leave me feeling motivated and empowered You have a gift for inspiring others and it’s evident in your writing

发表回复

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