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

/ 4,941评论 / 17091阅读 / 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. airhostess说道:

    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

  2. Matthewnouts说道:

    buy cytotec online fast delivery: cytotec abortion pill – buy cytotec online

  3. Matthewnouts说道:

    cytotec pills buy online: Cytotec 200mcg price – buy cytotec online fast delivery

  4. KevinBlupt说道:

    nolvadex 10mg: tamoxifen benefits – tamoxifen premenopausal

  5. KevinBlupt说道:

    buy prednisone 5mg canada: prednisone 10mg – prednisone 20mg online without prescription

  6. Tooft说道:

    The American streaming service announced today that it secured exclusive broadcast rights for the Premier League in Canada. Beginning next season on a three-year deal, it will replace DAZN as the country’s broadcaster for England’s top soccer league. DAZN, the revolutionary live and on-demand sport service, announced that it will be expanding into its fifth territory – Canada. DAZN is one of the most popular streaming services in Canada for sports fans. It’s a great place for watching live sports action like NFL games and Champions League football. However, it’s not the only Canadian sports service out there. In this guide, we’ll be looking at some of the top DAZN alternatives for Canadian sports fans to choose.
    http://w.ballpennara.com/bbs/board.php?bo_table=free&wr_id=24944
    Manchester United finished second in their group, losing out on the top spot to Spanish side Real Sociedad by goal difference. They will face Barcelona, who finished third to Bayern Munich and Inter Milan in their Champions League group. This match between former Champions League winners will be the headline clash of the UEFA Europa League playoffs 2022-23.  They face a Frankfurt side that eased their way past West Ham United in the semi-finals, and are now looking to lift the trophy for the second time in their history. Not a member? Join today \n Al momento abbiamo problemi con il servizio. Mentre lavoriamo per risolverli\n puoi continuare a guardare gli eventi live selezionando l’opzione di\n seguito.\n Although both semi-final matches will air on the BBC TV channel, the first semi-final match between Manchester City and Sheffield United will only be available for streaming on the ITVX platform. The second semi-final match between Brighton & Hove Albion and Manchester United will stream on BBC iPlayer. Both matches will stream on ESPN+ and Hulu.

  7. Matthewnouts说道:

    buy cytotec pills online cheap: buy cytotec over the counter – buy cytotec online

  8. KevinBlupt说道:

    buy cytotec pills: cytotec buy online usa – buy cytotec over the counter

  9. wiresuk说道:

    Somebody essentially lend a hand to make significantly posts I might state That is the very first time I frequented your web page and up to now I surprised with the research you made to create this particular put up amazing Excellent job

  10. etruesports说道:

    What i dont understood is in reality how youre now not really a lot more smartlyfavored than you might be now Youre very intelligent You understand therefore significantly in terms of this topic produced me personally believe it from a lot of numerous angles Its like women and men are not interested except it is one thing to accomplish with Woman gaga Your own stuffs outstanding Always care for it up

  11. Robertperma说道:

    prednisone brand name prednisone 40 mg tablet prednisone 5 tablets

  12. LewisToite说道:

    http://zithromaxbestprice.pro/# buy zithromax online fast shipping

  13. Matthewnouts说道:

    buy cytotec online: buy cytotec pills online cheap – Misoprostol 200 mg buy online

  14. Matthewnouts说道:

    zithromax drug: how to get zithromax – where to buy zithromax in canada

  15. Matthewnouts说道:

    cost generic propecia without a prescription: buying cheap propecia price – get cheap propecia

  16. Robertperma说道:

    buy propecia now get propecia price cost of propecia without insurance

  17. Robertperma说道:

    tamoxifen and grapefruit clomid nolvadex nolvadex d

  18. Pretty! This was an incredibly wonderful post. Thanks for providing these details.

  19. Robertperma说道:

    buying generic propecia propecia order cost of generic propecia without dr prescription

  20. LewisToite说道:

    https://prednisonebestprice.pro/# prednisone 20 mg tablet price

  21. Matthewnouts说道:

    zithromax 500 without prescription: zithromax for sale online – zithromax capsules 250mg

  22. LewisToite说道:

    https://cytotecbestprice.pro/# buy cytotec pills online cheap

  23. Robertperma说道:

    generic zithromax 500mg how to get zithromax over the counter how much is zithromax 250 mg

  24. PatrickHindy说道:

    http://prednisonebestprice.pro/# prednisone without prescription.net

  25. Matthewnouts说道:

    prednisone 20 mg tablet: prednisone 10mg tablet cost – prednisone pill prices

  26. PatrickHindy说道:

    http://propeciabestprice.pro/# buying propecia for sale

  27. Matthewnouts说道:

    where can you buy prednisone: where to buy prednisone uk – prednisone online paypal

  28. PatrickHindy说道:

    https://zithromaxbestprice.pro/# zithromax capsules

  29. Robertperma说道:

    purchase prednisone from india prednisone nz cost of prednisone 5mg tablets

  30. Public policy responses addressing causes and effects of income inequality in the US include: progressive tax incidence adjustments, strengthening social safety net provisions such as Aid to Families with Dependent Children, welfare, the food stamp program, Social Security, Medicare, and Medicaid, organizing community interest groups, increasing and reforming higher education subsidies, increasing infrastructure spending, and placing limits on and taxing rent-seeking.

  31. Matthewnouts说道:

    how does tamoxifen work: tamoxifen menopause – tamoxifen warning

  32. Robertperma说道:

    common side effects of tamoxifen tamoxifen lawsuit tamoxifen medication

  33. LewisToite说道:

    https://zithromaxbestprice.pro/# buy zithromax 1000mg online

  34. Robertperma说道:

    cost of tamoxifen tamoxifen adverse effects tamoxifen side effects forum

  35. PatrickHindy说道:

    http://propeciabestprice.pro/# get propecia tablets

  36. Matthewnouts说道:

    15 mg prednisone daily: 6 prednisone – prednisone 10mg cost

  37. Robertperma说道:

    tamoxifen hot flashes tamoxifen citrate pct tamoxifen breast cancer

  38. LewisToite说道:

    http://nolvadexbestprice.pro/# tamoxifen hot flashes

  39. LewisToite说道:

    http://propeciabestprice.pro/# get cheap propecia without a prescription

  40. PatrickHindy说道:

    http://prednisonebestprice.pro/# where to buy prednisone uk

  41. Matthewnouts说道:

    liquid tamoxifen: tamoxifen and antidepressants – effexor and tamoxifen

  42. PatrickHindy说道:

    http://cytotecbestprice.pro/# cytotec buy online usa

  43. Matthewnouts说道:

    order cheap propecia without dr prescription: cost cheap propecia without a prescription – buying cheap propecia without dr prescription

  44. Robertperma说道:

    order cheap propecia price cost cheap propecia pill cost of cheap propecia pill

  45. Robertperma说道:

    buy cytotec over the counter purchase cytotec order cytotec online

  46. PatrickHindy说道:

    https://propeciabestprice.pro/# buy cheap propecia pill

  47. Matthewnouts说道:

    generic zithromax online paypal: can you buy zithromax over the counter in canada – can i buy zithromax over the counter in canada

发表回复

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