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

/ 1,229评论 / 5220阅读 / 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. this article说道:

    You’re so awesome! I don’t suppose I’ve read a single thing like that before. So great to discover someone with original thoughts on this subject. Really.. thank you for starting this up. This site is something that’s needed on the internet, someone with a bit of originality.

  2. online slot说道:

    porn cannibalism

  3. Jamesjer说道:

    buy cipro online without prescription: buy cipro online – buy cipro online canada

  4. ThomasInace说道:

    https://doxycyclinedelivery.pro/# doxycycline hydrochloride 100mg

  5. Jamesjer说道:

    amoxicillin 500mg buy online uk: amoxicillin 500mg capsule cost – amoxicillin capsule 500mg price

  6. ThomasInace说道:

    https://amoxildelivery.pro/# generic for amoxicillin

  7. ThomasInace说道:

    http://paxloviddelivery.pro/# Paxlovid over the counter

  8. Good information. Lucky me I found your blog by accident (stumbleupon). I’ve bookmarked it for later!

  9. ThomasInace说道:

    http://paxloviddelivery.pro/# paxlovid pharmacy

  10. Jamesjer说道:

    doxycycline tablets australia: cost of doxycycline in canada – buy doxycycline monohydrate

  11. ThomasInace说道:

    http://paxloviddelivery.pro/# paxlovid pharmacy

  12. kids cloths说道:

    The very next time I read a blog, I hope that it does not disappoint me as much as this particular one. After all, I know it was my choice to read through, however I really believed you would probably have something helpful to talk about. All I hear is a bunch of moaning about something that you could possibly fix if you weren’t too busy searching for attention.

  13. Jamesjer说道:

    buying generic clomid prices: how can i get generic clomid without insurance – generic clomid tablets

  14. Jamesjer说道:

    amoxicillin in india: amoxicillin pharmacy price – can we buy amoxcillin 500mg on ebay without prescription

  15. Jamesjer说道:

    cipro online no prescription in the usa: cipro ciprofloxacin – ciprofloxacin generic price

  16. Spot on with this write-up, I really believe that this website needs a lot more attention. I’ll probably be back again to read more, thanks for the information!

  17. Its like you read my mind You appear to know so much about this like you wrote the book in it or something I think that you can do with a few pics to drive the message home a little bit but instead of that this is excellent blog A fantastic read Ill certainly be back

  18. ThomasInace说道:

    http://amoxildelivery.pro/# amoxicillin 250 mg capsule

  19. kubet77说道:

    That is a very good tip especially to those new to the blogosphere. Brief but very precise information… Thanks for sharing this one. A must read article.

  20. Jamesjer说道:

    ciprofloxacin: buy ciprofloxacin over the counter – buy cipro online canada

  21. Hi! I could have sworn I’ve visited this web site before but after going through a few of the posts I realized it’s new to me. Regardless, I’m definitely happy I came across it and I’ll be book-marking it and checking back often.

  22. Jamesjer说道:

    buy ciprofloxacin: cipro ciprofloxacin – ciprofloxacin generic

  23. iptv说道:

    Pretty! This was a really wonderful article. Many thanks for providing this info.

  24. Jamesjer说道:

    can you get clomid without prescription: how can i get cheap clomid price – how can i get clomid

  25. ThomasInace说道:

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

发表回复

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