目录
模板
- 使用模板我们就可以写一个函数,而它的参数可以接收多种类型。比如:
// 普通函数, 只能接受 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;
}
I was pretty pleased to uncover this web site. I want to to thank you for ones time for this particularly fantastic read!! I definitely really liked every bit of it and I have you bookmarked to check out new stuff in your blog.
hacklink
I’m pretty pleased to discover this website. I want to to thank you for your time for this wonderful read!! I definitely really liked every little bit of it and I have you saved to fav to see new information in your website.
An impressive share! I have just forwarded this onto a friend who has been conducting a little homework on this. And he in fact ordered me lunch simply because I found it for him… lol. So allow me to reword this…. Thanks for the meal!! But yeah, thanks for spending time to talk about this issue here on your website.
lgbt porn
Having read this I thought it was extremely enlightening. I appreciate you spending some time and energy to put this content together. I once again find myself spending a lot of time both reading and commenting. But so what, it was still worthwhile!
Thank you for some other great post. The place else may anyone get that type of info in such a perfect manner of writing? I have a presentation next week, and I am on the look for such information.
It’s actually a great and helpful piece of information. I am happy that you just shared this useful information with us. Please stay us informed like this. Thanks for sharing.
I need to to thank you for this good read!! I absolutely enjoyed every bit of it. I have you bookmarked to look at new stuff you post…
Very good info. Lucky me I recently found your blog by chance (stumbleupon). I have book-marked it for later.
https://artdaily.com/news/171650/Mp3Juice-Review–The-Pros-and-Cons-You-Need-to-Know
casino
bookmarked!!, I like your site.
Hi there, I do believe your blog may be having browser compatibility problems. When I take a look at your blog in Safari, it looks fine but when opening in I.E., it has some overlapping issues. I just wanted to provide you with a quick heads up! Other than that, wonderful website.
Greetings! Very helpful advice within this article! It is the little changes that will make the biggest changes. Many thanks for sharing!
online slot
You have brought up a very superb points, thanks for the post.
Next time I read a blog, Hopefully it won’t disappoint me just as much as this one. I mean, Yes, it was my choice to read, nonetheless I truly thought you’d have something helpful to say. All I hear is a bunch of complaining about something you could fix if you weren’t too busy searching for attention.
I seriously love your site.. Very nice colors & theme. Did you create this site yourself? Please reply back as I’m hoping to create my own personal site and want to find out where you got this from or what the theme is named. Thanks!
Nice post. I find out something much harder on different blogs everyday. Most commonly it is stimulating to read content using their company writers and use something from their site. I’d want to use some while using content on my own blog no matter whether you do not mind. Natually I’ll offer you a link in your web weblog. Thank you sharing.
I do believe you will find there’s problem with your site making use of Internet explorer browser.
Genial der Artikel ist wirklich gut mach weiter so Viele Grüsse Saloma
I believe you have remarked some very interesting details , thankyou for the post.
Saved as a favorite, I like your website!
I believe there’s a issue with your blog working with Safari internet browser.
hacklink
Anecdotally, I’ve spoken to many mothers who have told me stories about the pleasures of playing video games with their children. For example, at one recent birthday party, a mother proudly told me how she, plays Clash of Clans with her sons, and that her parents have even gotten in on the game; three generations, all playing together. Follow us on social media to stay up to date on everything we’re doing. Game Mess Mornings 06 05 24 If you want to show your mother how much you love her, buy her a video game this Mother’s Day. Mother’s Day Trivia: Test your knowledge of all things Mother’s Day in this themed trivia game that promises fun for everyone. Mother’s Day games ideas to make the most of one of the biggest holidays in the calendar in terms of consumer spending. In the US it’s the third highest spending holiday, only behind Christmas and Valentine’s, and in the UK Mother’s Day generates close to £2 billion in consumer spending.
https://mariolhcw406308.blogpayz.com/27490302/google-games-t-rex
While Checkers is not quite as popular as a game like Chess, there is still a lot of strategy involved. Not to worry though, there are a few key strategies that you can use to win some games. GameTable is an interactive game company that offers an online checkers game. In this simple game, you can choose a one or two-player version. In either option, you can select themes, the board size, forced jumps available, and to show your moves. In the single-player, you can also choose from easy to expert. Once play begins, you have the option to get hints and reverse moves. This site also features a how-to-play section, history, and rules. © 2018 CoolGames All Rights Reserved It is recommended to follow the following instructions; in order to play checkers game and win in a professional way they are
I am curious to find out what blog system you happen to be using? I’m experiencing some minor security problems with my latest website and I’d like to find something more safe. Do you have any suggestions?
Glad to be one of the visitors on this awesome site : D.
I dugg some of you post as I cerebrated they were very beneficial handy
Appreciate it to get a incredibly apparent and very helpful publish. I’m positively a violator of many of these rules. I generally uncover personally conflicted when producing a blog posting because I see myself personally creating more than people prefer to read, but I feel that I have got to do the subject matter proper rights by completely protecting it. I think that by pursuing some of these policies I finish up cutting out critical factors to the dialogue. I guess you could have to acquire a stability.
Sewing Machines… […]plenty of time to read through as well as visit the articles as well as sites we have now linked to[…]…
xxx
Aw, this was a very good post. Taking a few minutes and actual effort to generate a great article… but what can I say… I put things off a whole lot and never manage to get anything done.
slot
I have read some excellent stuff here Definitely value bookmarking for revisiting I wonder how much effort you put to make the sort of excellent informative website
Next time I read a blog, Hopefully it won’t fail me just as much as this particular one. I mean, I know it was my choice to read, nonetheless I really believed you would have something useful to talk about. All I hear is a bunch of complaining about something you could fix if you weren’t too busy searching for attention.
buying prescription drugs in mexico
https://cmqpharma.com/# mexican drugstore online
п»їbest mexican online pharmacies
mexico drug stores pharmacies: online mexican pharmacy – buying prescription drugs in mexico online
I admire the depth of your research.검색엔진최적화 업체
This is a crucial topic—thanks for addressing it.프라그마틱 슬롯 하는법
Hello! I just would like to give a huge thumbs up for the great info you have here on this post. I will be coming back to your blog for more soon.
This is exactly what I needed to read today.대출 갈아타기
귀하의 웹사이트에 이러한 귀중한 정보를 제공해 주셔서 감사합니다. 나는 그것들이 매우 유용하다는 것을 알았고 더 많은 것을 배우기 위해 확실히 돌아올 것입니다.
I’m sharing this with my community.프리랜서 대출
Very good article. I definitely love this website. Continue the good work!
This web site certainly has all the info I wanted about this subject and didn’t know who to ask.
https://qqfwgxwcwqwcqhi.carinsurancequotes21c.info/ .bMqyUwXMZzy
This site was… how do you say it? Relevant!! Finally I have found something which helped me. Thank you.
This is the perfect web site for anybody who would like to understand this topic. You understand so much its almost tough to argue with you (not that I actually will need to…HaHa). You definitely put a fresh spin on a subject that’s been written about for decades. Great stuff, just excellent.