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

/ 95评论 / 1324阅读 / 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. najlepszy sklep说道:

    Wow, incredible blog structure! How lengthy have
    you been running a blog for? you make blogging look easy.
    The entire look of your site is great, let alone the content material!
    You can see similar here sklep internetowy

  2. hitman.agency说道:

    Hello! Do you know if they make any plugins to assist with SEO?
    I’m trying to get my website to rank for some targeted keywords but I’m not
    seeing very good gains. If you know of any please share.
    Kudos! I saw similar blog here: Scrapebox List

  3. ladesbet フェチポルノ ladestinemi.d1CGlnvG5cU

  4. ladesbet swinger ਪੋਰਨ ਹੈ ladesinemi.BKIx6U0bNYZ

  5. Good day! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my website to rank for
    some targeted keywords but I’m not seeing very good
    gains. If you know of any please share. Kudos! I saw
    similar article here: GSA Verified List

  6. ਵੱਡੇ ਗਧੇ ਪੋਰਨ madisonivysex.jIPFDWqzDIU

  7. लैटिन अश्लील साहित्य hkyonet.5BRyVDGmNLq

  8. छोटे स्तन अश्लील txechdyzxca.4Iai4JSznuS

  9. बीबीडब्ल्यू पोर्न के बा hjkvbasdfzxzz.iqmgeXG2zKn

  10. बुत अश्लील qqyyooppxx.8cSNUQhmWlv

  11. fashionflag porn hd.com download fashionflag.gPc1IdA5Atc

  12. It’s very interesting! If you need help, look here: ARA Agency

  13. najlepszy sklep说道:

    Hi there! Do you know if they make any plugins to assist with SEO?
    I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good
    gains. If you know of any please share. Thanks! You can read similar text here:
    Sklep internetowy

  14. Wow, awesome blog structure! How long have you been blogging for?
    you made blogging glance easy. The whole glance of your website is wonderful, as well as the content!

    You can see similar here najlepszy sklep

  15. Howdy are using WordPress for your blog platform? I’m new to the blog world but I’m trying
    to get started and create my own. Do you require any coding expertise to make your own blog?
    Any help would be really appreciated! I saw similar here: E-commerce

  16. Howdy! I just wish to give you a big thumbs up for the great info you have here on this post.
    I will be coming back to your blog for more soon. I saw similar
    here: Dobry sklep

  17. e-commerce说道:

    Wow, superb blog structure! How lengthy have you ever been blogging for?
    you made blogging look easy. The entire look of your site is magnificent, as
    smartly as the content material! You can see similar here sklep internetowy

  18. dobry sklep说道:

    Wow, fantastic blog structure! How lengthy have you ever been blogging
    for? you make blogging glance easy. The total glance of your site is wonderful, let alone the content material!
    You can see similar here najlepszy sklep

  19. xxx hd porno video ggjinnysflogg.PyJhzwuBq8Q

  20. pron 4k video download ggjennifegg.bAxcNrZYjmm

  21. pornky com说道:

    porn download in 4k gghkyogg.p6OwIplaJRv

  22. temp mail说道:

    This is a nice blog as well. Your webpage loads quite quickly. Which hosting service are you using? I would like your affiliate link. My webpage should load just as rapidly.

  23. temp mail说道:

    I’m grateful. I have been looking for information on this subject for a time, and this is the best resource I have discovered thus far. What about the bottom line, though? Do you know for sure what the supply is?

  24. Wow superb blog layout How long have you been blogging for you make blogging look easy The overall look of your site is magnificent as well as the content

  25. temp mail说道:

    Hello, I thought you had looked at my blog, so I came back to say hello. Since I’m trying to improve my website, I suppose I can use some of your advice.

  26. porn sex说道:

    watch porn video tthighereduhryyy.CEEMPYj4H9c

  27. porno izle说道:

    porno izle vvsetohimalxxvc.dgi19k6PzJOF

  28. porn sex eyeconartxx.8dfpFKMzoUVn

  29. viagra说道:

    bahis siteleri porn sex incest 250tldenemebonusuxx.AIJMqo3tsaif

  30. porno说道:

    sexax bingoxx.fhzLwElfXcow

  31. escort说道:

    anal siteleri mobileidn.eQ8t7OlDOyr1

  32. sexx说道:

    anal siteleri footballxx.XZNdsgTG2Dth

  33. amciik siteleri说道:

    pornhub bahis siteleri pokkerx.8Rob5tA1gT4a

发表回复

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