目录
模板
- 使用模板我们就可以写一个函数,而它的参数可以接收多种类型。比如:
// 普通函数, 只能接受 int 类型参数,如果传入其他类型需要类型转换
int sum(int a, int b) {
return (a + b);
}
double sum(double a, double b) {
return (a + b);
}
- 由于不管是 int 参数、double参数,我们的 sum 函数求和内部代码都是一样的 (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);
}
- c++的模板是编译期就会展开的,编译期会根据你使用到的类型,生成 template <int> ... 版本、template<double> ... 版本,而原本写的 template<T> ... 其实就是一个配置一样,运行时是不存在的,只是为了告诉编译期应该怎么生成代码。
可变参数模板
- 上面的求和只能2个数求和,那我如果有3个、4个、5个 ... 呢,难道要都写一遍吗:
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) {
// 展开求和
}
- 但展开这个参数包 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);
}
- 最后一个函数 T sum(T... args) 才是我们暴露给用户使用的函数,而它其实是把参数包 args 转给了mysum(T item, T... args),可见原本在 sum 的参数包被拆出第一个参数 item,和剩下的其他参数 args 调用 mysum,假如 args 不存在,则是直接调用了 mysum(T item)
- 而 mysum(T item, T... args) 干嘛了呢, 它将 item 传给 mysum(T item) 处理,并将剩下的传给了"自己"!是的,此时其实就是递归,但请注意,以往我们递归调用的是函数本身,但这次递归不一样,举个例子来看看:
- 假如我们现在要调用 sum 了:sum(1, 2, 3, 4, 5),编译器就会生成接受5个参数的sum:
int sum(int arg0, int arg1, int arg2, int arg3, int arg4);
- 然后sum里面又调用了mysum,编译器接着按照mysum的声明,拆分sum传过来的5个参数为1 + 4生成:
int mysum(int item, int arg1, int arg2, int arg3, int arg4);
- 那接下来就看这个参数列表是 1+4 的mysum里面了,编译器先生成 mysum(T) 对应的 mysum(int):
int mysum(int item);
- 然后1+4的mysum里还把剩下的4个参数递归传给了自己这个模板,那就得把 4 再拆分成 1 + 3 生成mysum
int mysum(int item, int arg2, int arg3, int arg4);
- 到这里你可能已经理解它是怎么拆参数包的了,虽然叫递归,但其实每一次拆包调用的并不是函数本身,而是源于同一个模板生成的少一个参数的函数。
- 再往下就是接着生成:
int mysum(int item, int arg3, int arg4);
int mysum(int item, int arg4);
- 最终参数包 args 只有一个参数时就不用再生成了,它会直接去调用之前生成的 mysum(T item)
不定类型数量
- 前面的可变参数模板还不够彻底,它生成的函数接受的类型只有一个 T,那我能不能每一个参数类型都不一样呢?那么就需要对 template 那一行动手脚了:
template<typename T1, typename T2, typename ...Args>
T1 mysum(T2 item, Args... args);
- 可以看到,template内,我们单独声明了 返回值类型是 T1,第一个参数类型是 T2,而后面的参数类型则不确定,因此用 typename...Args 声明,在 mysum 的参数列表中 (T2 item, Args... args),Args...就表示args的数量是不确定的,由于Args本身类型数量也不确定,因此整体就表示 这里可以接受多个相同或不同类型的参数。
实现printf
- 有了上面的知识,实现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;
}
Link exchange is nothing else however it is simply placing the other person’s blog link on your page at proper place and other person will also do same in support
of you.
Link exchange is nothing else however it is just placing the other person’s weblog
link on your page at appropriate place and other person will also do similar
in favor of you.
I pay a quick visit everyday some sites and websites to read content, except
this webpage presents feature based articles.
I really like what you guys are up too. This kind of clever work and reporting!
Keep up the good works guys I’ve added you guys to our blogroll.
https://denemebonusuverensiteler.win/# bahis siteleri
Hi there friends, its impressive post regarding educationand fully explained, keep it up all the time.
Hey are using WordPress for your site platform?
I’m new to the blog world but I’m trying to get started and create my own. Do you require
any coding knowledge to make your own blog? Any
help would be greatly appreciated!
Your means of telling all in this article is in fact pleasant,
every one can without difficulty understand it, Thanks a lot.
It’s actually a great and useful piece of information. I’m satisfied that you simply shared this useful info with us.
Please keep us informed like this. Thanks for sharing.
Hello there, You have done an incredible job.
I’ll certainly digg it and personally suggest to my friends.
I’m confident they will be benefited from this website.
Appreciating the time and effort you put into your blog and in depth information you provide.
It’s great to come across a blog every once in a while that isn’t the same out of date rehashed information. Great read!
I’ve saved your site and I’m including your RSS feeds to my Google account.
Greetings! Very helpful advice in this particular post!
It is the little changes which will make the most significant changes.
Many thanks for sharing!
en iyi slot siteleri 2024: deneme bonusu veren siteler – slot casino siteleri
Great article. I’m experiencing many of these issues as well..
https://sweetbonanza.network/# sweet bonanza demo oyna
slot kumar siteleri: slot siteleri bonus veren – deneme veren slot siteleri
https://denemebonusuverensiteler.win/# bonus veren siteler
Twenty years again IT firms hardly ever had any presence in India and for that reason weren’t a part of the indices.
Let’s start with how to sign up for your own PayPal account.
If you do not take control of your individual retirement investing and educate yourself on different funding options you’ll lose purchasing power and your retirement accounts will most likely lose another 30 – 40 like we just saw with a few of the foremost financial problems we’re seeing.
@クレヨン しんちゃん 22 ventolin prices in canada: Ventolin inhaler best price – where to buy ventolin singapore
can you buy ventolin over the counter in usa
Moreover, in the world of business customer happiness yields benefit for the firms.
Hence you can take different control options, like calling a maintenance company to check your stove or checking with your neighbor if you can use his/her stove in case yours fail.
https://slotsiteleri.bid/# guvenilir slot siteleri 2024
slot casino siteleri: en guvenilir slot siteleri – deneme bonusu veren siteler
en iyi slot siteleri 2024: slot oyun siteleri – slot siteleri
http://denemebonusuverensiteler.win/# deneme bonusu
en iyi slot siteler: en yeni slot siteleri – deneme bonusu veren siteler
Hello there! I could have sworn I’ve been to this web site before but after browsing through a few of the articles I realized it’s new to me. Anyways, I’m definitely delighted I discovered it and I’ll be book-marking it and checking back often.
en iyi slot siteleri 2024: slot siteleri guvenilir – slot siteleri guvenilir
deneme bonusu veren slot siteleri: casino slot siteleri – slot kumar siteleri
http://sweetbonanza.network/# sweet bonanza demo
guvenilir slot siteleri 2024: deneme bonusu veren siteler – en iyi slot siteleri 2024
https://slotsiteleri.bid/# canl? slot siteleri
https://sweetbonanza.network/# sweet bonanza
Hi, I do believe this is an excellent website. I stumbledupon it 😉 I will return once again since I saved as a favorite it. Money and freedom is the greatest way to change, may you be rich and continue to help other people.
Wonderful article! We are linking to this particularly great post on our website. Keep up the good writing.
ремонт iphone
An outstanding share! I’ve just forwarded this onto a coworker who had been conducting a little research on this. And he in fact bought me dinner due to the fact that I found it for him… lol. So let me reword this…. Thank YOU for the meal!! But yeah, thanks for spending some time to talk about this topic here on your website.
นี่เป็นบทความที่เขียนได้ดีและให้ข้อมูลดีมาก ฉันได้เรียนรู้อะไรมากมายจากการอ่านบทความนี้
Chen was open about his plans for BlackBerry upon becoming a member of the company, saying his intent to maneuver away from hardware manufacturing to deal with enterprise software program corresponding to QNX, BlackBerry UEM, and AtHoc.
Murray — like Briggs, Budd, and Hayes — provided a design service to shoppers like Graham who have been too small to make use of a full-time styling operation.
One of the exchange’s largest brokerage firms, Moore & Schley, was closely in debt and in danger of collapse.
Treasury Secretary Timothy Geithner, then President and CEO of the NY Federal Reserve Bank, placed significant blame for the freezing of credit score markets on a “run” on the entities in the “parallel” banking system, additionally referred to as the shadow banking system.
To see who has despatched you money, visit the Activity tab on the Cash App residence display screen.
Next time I read a blog, Hopefully it doesn’t fail me just as much as this particular one. After all, I know it was my choice to read, but I actually thought you would have something interesting to talk about. All I hear is a bunch of crying about something that you can fix if you weren’t too busy seeking attention.
BaddieHub You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!
Aw, this was a really nice post. Spending some time and actual effort to create a really good article… but what can I say… I procrastinate a lot and never seem to get nearly anything done.
Профессиональный сервисный центр по ремонту ноутбуков и компьютеров.дронов.
Мы предлагаем:починка ноутбука
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Профессиональный сервисный центр по ремонту сотовых телефонов, смартфонов и мобильных устройств.
Мы предлагаем: ремонт телефона
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
yasal slot siteleri: slot siteleri guvenilir – guvenilir slot siteleri 2024