目录
模板
- 使用模板我们就可以写一个函数,而它的参数可以接收多种类型。比如:
// 普通函数, 只能接受 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;
}
zestril no prescription: Lisinopril refill online – zestril 40 mg
lisinopril 20g: Lisinopril refill online – cheap lisinopril 40 mg
I love reading through an article that will make people think. Also, thank you for allowing for me to comment.
http://lipitor.guru/# lipitor over the counter
lasix furosemide online lasix 40mg
https://cytotec.pro/# buy cytotec
generic lasix lasix generic lasix 100 mg tablet
cytotec pills buy online: Misoprostol price in pharmacy – cytotec online
buy cytotec over the counter Misoprostol price in pharmacy cytotec buy online usa
http://lisinopril.guru/# lisinopril 4214
http://lipitor.guru/# buy lipitor online
buy misoprostol over the counter https://lisinopril.guru/# lisinopril online without prescription
lasix medication
This page is not available. Return to Home Page Belka, is back. Still a belter… Anastasia Brokelyn has returned from the beach with only her bikini and flimsy top. She doesn’t seem to unhappy about it, however… RULES – Students Playing Strip Poker, Things Get Crazy! Yo! Calling all strip poker fans out there! Want to have some fun with international poker players and see them strip for your pleasure? Check out My Strip Poker today and have yourself some fun! Your email address will not be published. Required fields are marked * Tawnee Stone and Dirty ali strip poker FIST4K. Stud fists GFs pussy after they play strip poker in kitchen This website contains age-restricted materials including nudity and explicit depictions of sexual activity. By entering, you affirm that you are at least 18 years of age or the age of majority in the jurisdiction you are accessing the website from and you consent to viewing sexually explicit content.
https://jaspervogn854119.aboutyoublog.com/28295968/baccarat-game-news
At Wild Joker Online Casino, we are not only generous with our free spins and bonuses on our great online pokies, but we also provide the best online casino welcome offer you won’t find anywhere else. Take this WILD welcome offer now: A valuable diamond in 3 places on the middle reels pays 1x the stake, and then awards a spin on wheel of fortune. The 10 segments of the wheel hold from 10 free spins with a 2x multiplier on all wins, to 30 free games where all wins are tripled. Multipliers don’t apply to Joker wins though. You can retrigger the free games with 3 more scatter symbols on any spin. There are currently no known player issues pertaining to how Wild Joker Casino conducts their gaming operations. Founded in the U.S. state of Georgia in 1998, RealTime Gaming represents decades of experience. RTG is right at the top with industry leaders like Microgaming and NetEnt, providing games from their diverse library to dozens of online casinos, Wild Joker Casino included.
buy cytotec over the counter https://tamoxifen.bid/# tamoxifen pill
lasix 20 mg
generic lasix: furosemide online – buy lasix online
lasix: furosemide online – furosemide 100 mg
lisinopril pill 10mg cheap lisinopril how to buy lisinopril online
order cytotec online http://furosemide.win/# lasix 100 mg
furosemide 100mg
Hello there, I do believe your web site could possibly be having internet browser compatibility problems. Whenever I look at your site in Safari, it looks fine however, when opening in IE, it has some overlapping issues. I just wanted to provide you with a quick heads up! Apart from that, wonderful website!
nolvadex d buy tamoxifen online nolvadex vs clomid
lipitor 10 mg cost: Atorvastatin 20 mg buy online – buy lipitor cheap
cytotec buy online usa buy cytotec in usa buy cytotec over the counter
buy cytotec over the counter https://tamoxifen.bid/# raloxifene vs tamoxifen
lasix furosemide 40 mg
https://lipitor.guru/# lowest price lipitor
buy cytotec pills online cheap cheapest cytotec buy cytotec online fast delivery
https://lipitor.guru/# lipitor 4 mg
Way cool! Some extremely valid points! I appreciate you writing this article and the rest of the website is really good.
I was just as enthralled by your work as you were. The visual presentation is refined, and the written content is sophisticated. However, you seem anxious about the possibility of presenting something that could be perceived as questionable. I believe you’ll be able to rectify this matter in a timely manner.
Very good info. Lucky me I recently found your blog by chance (stumbleupon). I’ve book marked it for later.
Nice post. I learn something new and challenging on websites I stumbleupon on a daily basis. It will always be interesting to read through articles from other writers and practice something from their websites.
I always was interested in this topic and still am, regards for putting up.
I used to be able to find good information from your content.
Board game box pricing increases with the dimensions of the box, meaning it’s uneconomical to choose a large box for a game with few pieces. Most industry leaders recommend against using a big box for a game with few components. Thanks for sharing this blog. The story your telling about how to make a classic board game box. The detail was outstanding and up to the mark. I pin this website for more interesting articles in future. And this could help me to make my Vape Cartridge Boxes like this one. We make our magnetic closure rigid boxes in the same high-quality materials as telescope boxes and with the same comprehensive range of options for covering, printing, and special finishes. The key difference is that these boxes have hinged lids or a folding design and they’re closed with a powerful magnetic catch. Ideal as a luxury-level stretch goal for your Kickstarter campaign or simply as a high-end solution to your game boxing needs. As with all our boxes, you can also insert a cardboard or plastic tray to house the game pieces or fill them with cut-out foam inserts for a very professional look.
https://rowanxvab963319.blog2freedom.com/28650916/math-matching-games
Setup recurring reminders by selecting tournament options like team size and game mode. Once a tournament is about to start, we will send you a push notification! In Rocket League, each team may have a maximum of six (6) players, broken down into three (3) starting players on the Roster, and three (3) substitutes on the Bench. No individual may simultaneously hold two or more roles as listed above. All players and coaches are expected to be present physically or virtually for all official PlayVS matches. Both the Roster and Bench must be finalized prior to the Roster Lock Date. The client will automatically generate a 32-team, single elimination bracket event, and upon reaching both Semifinals and Finals, players will play in a best of three match format. At first, Competitive Tournaments will be 3v3 that supports parties of all sizes, so a squad of three friends will face off against a solo-queued group. In this case, it might be a good idea to form up with some friends and communicate for a more coordinated approach, something that is not necessary in casual play, but probably an important component of competitive matches.
HEX price is $0.001603, up 9.78% in the last 24 hours, and the live market cap is $0. It has circulating supply of 0 HEX coins and a max supply of 598,857,169,162 HEX alongside $236,610 24h trading volume. The choice of colors for the Bitcoin brand is deliberate. The orange color is associated with energy, excitement, and innovation. The gray color is associated with trust, security, and stability. The white color is associated with purity, simplicity, and clarity. HEX uses the Ethereum network for the transaction layer (sending and receiving HEX tokens, as well as interacting with the HEX smart contract), whilst the consensus code and staking mechanism is contained in the HEX smart contract. The potential approval of a spot Bitcoin ETF in the US would provide enhanced trust and mainstream recognition for Bitcoin and the broader cryptocurrency market. ETFs are well-established investment vehicles that are widely recognized and understood by investors. The launch of a spot Bitcoin ETF in the US would introduce a regulated and familiar way for traditional investors to gain exposure to Bitcoin, potentially attracting a wider range of participants, increasing overall market confidence, and leading to the launch of other crypto ETFs.
http://tmenter.net/bbs/board.php?bo_table=free&me_code=&wr_id=43966
Narrator: In the horse-breeding world, genetics is king. Wealthy investors are willing to pay high prices for proven winners’ semen, hoping that the resulting foal provides a large return on investment. ICO Price (USD) Market depth is a metric, which is showing the real liquidity of the markets. Due to rampant wash-trading and fake activity – volume currently isn’t the most reliable indicator in the crypto space. With so much money to be made in racing, show jumping, dressage, and more, the price of horse semen will remain stable. CUM alıp saklamak için bir kripto para borsasında veya P2P pazar aracılığıyla satın alma işlemi yapabilirsiniz. CUM aldıktan sonra bunu bir kripto cüzdanda güvenli olarak saklamanız önemlidir, bu cüzdanlar da iki türlüdür: sıcak cüzdanlar (yazılım tabanlı, fiziksel cihazlarınızda saklanır) ve soğuk cüzdanlar (donanım tabanlı, çevrimdışı olarak saklanır).
You’re so interesting! I do not think I’ve read through something like this before. So wonderful to find someone with genuine thoughts on this subject. Really.. thank you for starting this up. This web site is one thing that’s needed on the web, someone with a little originality.
You have made some decent points there. I checked on the internet for more info about the issue and found most individuals will go along with your views on this site.
Way cool! Some extremely valid points! I appreciate you penning this write-up plus the rest of the site is also really good.
indian pharmacy paypal: Indian pharmacy online – world pharmacy india
pharmacies in mexico that ship to usa: mexican pharmacy – medication from mexico pharmacy
cheapest online pharmacy india: top 10 online pharmacy in india – mail order pharmacy india
Way cool! Some very valid points! I appreciate you penning this post and the rest of the site is also really good.
bookmarked!!, I really like your site.
buy medicines online in india: Online medicine home delivery – world pharmacy india
ed pills for sale: ed pills online – cheap erection pills
buy medicines online in india: top 10 pharmacies in india – pharmacy website india
indian pharmacies safe: Indian pharmacy international shipping – cheapest online pharmacy india
Your writing has a way of resonating with me on a deep level. I appreciate the honesty and authenticity you bring to every post. Thank you for sharing your journey with us.
indianpharmacy com: Online medicine home delivery – buy prescription drugs from india
casino
ed rx online: Best ED pills non prescription – erectile dysfunction online