decltype in C++: Understand the details

Share the Article

decltype

The keyword decltype in C++, returns the data type of an expression or variable. This keyword works for any type, built-in or user-defined. Following example illustrates this behavior.

#include <iostream> //main header using namespace std; //namespace class MFPoint { }; int main() { int ia; //Built-in type cout << typeid(decltype(ia)).name() << endl; double db; //Built-in type cout << typeid(decltype(db)).name() << endl; MFPoint mfp; //User-defined type cout << typeid(decltype(mfp)).name() << endl; return 0; }

The output is:

i d 7MFPoint

Reference type information

The decltype also returns the information regarding reference. For instance, if the given input is a variable of type L-value reference, then decltype takes care of this. Following example, illustrates this with a normal variables and with both an L-value and and R-value reference.

#include <iostream> //main header using namespace std; //namespace class MFPoint { }; int main() { int ia0; //Not reference variable if(std::is_reference<decltype(ia0)>() ) cout << "Reference" << endl; else cout << "No reference" << endl; int &ia = ia0; //L-value reference if(std::is_reference<decltype(ia)>() ) cout << "Reference" << endl; else cout << "No reference" << endl; double &&db=1.1; //R-value reference if(std::is_reference<decltype(db)>() ) cout << "Reference" << endl; else cout << "No reference" << endl; MFPoint mfp0; MFPoint &mfp = mfp0; if(std::is_reference<decltype(mfp)>() ) cout << "Reference" << endl; else cout << "No reference" << endl; return 0; }

Output

No reference Reference Reference Reference

Additionally, the following program verifies that decltype is returning L-value and R-value reference information.

#include <iostream> //main header using namespace std; //namespace int main() { int ia0; if( std::is_reference<decltype(ia0)>() ) cout << "Reference" << endl; else cout << "No Reference" << endl; int &ia = ia0; if( std::is_reference<decltype(ia)>() ) { if(std::is_rvalue_reference<decltype(ia)>() ) cout << "R-value Reference" << endl; else cout << "L-rvalue Reference" << endl; } double &&db=1.1; if( std::is_reference<decltype(db)>() ) { if(std::is_rvalue_reference<decltype(db)>() ) cout << "R-value Reference" << endl; else cout << "L-rvalue Reference" << endl; } return 0; }

Output is as follows:

No Reference L-rvalue Reference R-value Reference

auto return type without trailing return type

In C++11, the main use of decltype is for the declaration of functions where function return type is auto. Therefore, in such cases, a trailing return type expressions guide the compiler to deduce the return type. For this reason, in the absence of a trailing type, the compiler shall generate error.

For instance, in the following example, there is no trailing return type for function “getValue”.

#include <iostream> //main header using namespace std; //namespace auto getValue(int ix) { int iy = ix; return iy; } int main() { return 0; }

The output from compiler is:

error due to non-usage of training return type from function

Following code show, how to add a trailing return type. Generally, the trailing type uses the type of parameters. In particular, this is very much useful in template functions.

auto getValue(int ix) -> decltype(ix) { int iy = ix; return iy; }

If the trailing return type expression is constructed using some variable which is not a parameter, then the compiler shall generate error. For example, in this code, the variable iy is inside in the function scope but not in parameters.

auto getValue(int ix) -> decltype(iy) { int iy = ix; return iy; }
compiler error due to incorrect trailing return type spec

Constructing trailing return type for template functions

#include <iostream> //main header using namespace std; //namespace template<typename T> auto getValue(T ix) -> decltype(ix) { T iy = ix; return iy; } int main() { getValue(4); return 0; }

Use in variable definition

Since, the decltype returns actual datatype of variable, therefore, such datatype can be used to define a variable.

The following example illustrates this:

#include <iostream> //main header using namespace std; //namespace int main() { int ix = 9; auto iy = ix; decltype(ix) x1; //x1 is int decltype(iy) y1; //y1 is int cout << typeid(x1).name() << endl; cout << typeid(y1).name() << endl; return 0; }

The output clearly shows both x1 and y1 become “int” type variable.

i i

decltype for L-value expressions

When we use decltype with complicated L-value expressions, the this returns L-value types. For example, decltype(x) is int, whereas, when this the name x is wrapped in parenthesis, (x), then it becomes an L-value expression. Therefore, now decltype((x)) shall return int&.

#include <iostream> //main header using namespace std; //namespace int main() { int iy; decltype(iy) iz = 8; // iy is int decltype((iy)) ik = iz; // (iy) is int& if(std::is_reference<decltype(iz)>()) cout << "Reference" << endl; else cout << "No Reference" << endl; if(std::is_reference<decltype(ik)>()) cout << "Reference" << endl; else cout << "No Reference" << endl; return 0; }

Output:

No Reference Reference

Main Funda: decltype always return type of the expression.

Related Topics:

What are dependent scope type in templates?
What is an implicit interface? 
Calling member functions in template base class
What is template meta programming (TMP)
How delete keyword can be used to filter polymorphism
Concept of Inline Functions
What is reference collapsing?
How std::forward( ) works?
How std::move() function works?
Smart Pointers: shared_ptr <T> 
Smart Pointers: unique_ptr<T>
What is move constructor ?
Understanding Constant Variables


Share the Article

1,098 thoughts on “decltype in C++: Understand the details

  1. hello!,I like your writing very much! share we communicate more about your article on AOL? I require an expert on this area to solve my problem. Maybe that’s you! Looking forward to see you.

  2. I may need your help. I tried many ways but couldn’t solve it, but after reading your article, I think you have a way to help me. I’m looking forward for your reply. Thanks.

  3. Pretty section of content. I simply stumbled upon your site and in accession capital to assert that I
    get in fact loved account your weblog posts. Anyway I’ll be subscribing to카지노사이트your feeds or even I achievement you get entry to constantly rapidly.

  4. Your writing is perfect and complete. baccaratsite However, I think it will be more wonderful if your post includes additional topics that I am thinking of. I have a lot of posts on my site similar to your topic. Would you like to visit once?

  5. เมื่อเล่นสล็อต สปินเกมเพลิน สล็อตแตกง่ายได้รางวัลใหญ่ ก็รับกำไรไปเลย นักเล่นหน้าใหม่ไม่เคยลองมาก่อน ก็สามารถทดลองเล่นสล็อตได้ เล่นฟรีไม่มีค่าใช้จ่าย เล่นที่สล็อตเว็บตรง ไม่ผ่านเอเย่นต์ เท่านั้น พีจีสล็อต

  6. เล่นสล็อตได้เงินง่าย สนุกสนานผ่อนคลายไปกับเกมสล็อต Spin Slot แตกหนักกำไรเพียบ ทุนน้อยก็เล่นแตกได้ เข้าแจ็คพอตรับโบนัสฟินๆ ได้ที่สล็อตเว็บตรง เว็บไซต์เกมสล็อตออนไลน์ยอดนิยมสูงสุด ณ ตอนนี้ สล็อตออนไลน์ ทั้งหมด

  7. สล็อตเว็บตรง ไม่ผ่านเอเย่นต์ เว็บหลักเกมสล็อตอัดแน่น รวมทุกค่ายดัง เว็บตรงผ่านมาตรฐานสากล วางใจได้หากเป็นสมาชิกกับเรา เข้าสู่ระบบกดรับโปรดี ดีลพิเศษได้อีกเพียบ แหล่งรวมสล็อตทุกค่าย เว็บเดียวจบ ทดลองเล่นpg

  8. มองหาความมันส์ เกมสล็อตแตกง่าย โปรดคลิกอย่าเลื่อนผ่าน สล็อตเว็บตรง ไม่ผ่านเอเย่นต์ รวมทุกค่ายดัง เล่นสล็อตแตกง่าย และเดิมพันออนไลน์ได้ครบจบในเว็บเดียว มีสล็อตค่ายดังให้เลือกเล่นครบครัน สล็อตทุกค่าย

  9. เข้าสู่ระบบเล่นสล็อตแตกง่าย ทำกำไรได้ไม่มีอั้น เล่นสล็อตทำเงิน เล่นทั้งวันก็ไม่มีเบื่อ สนุกมันส์ไปกับสล็อตเว็บตรง ไม่ผ่านเอเย่นต์ เล่นแตกได้เงินทันที สล็อตเล่นแตกหนัก ทำกำไรง่ายๆ ด้วยปลายนิ้วเดียว https://www.ambsuperslot.app

  10. It is in reality a nice and helpful piece of info. I am glad that you simply shared this useful information with us. Please keep us informed like this. Thank you for sharing.

  11. After reading your article, it reminded me of some things about gate io that I studied before. The content is similar to yours, but your thinking is very special, which gave me a different idea. Thank you. But I still have some questions I want to ask you, I will always pay attention. Thanks.

  12. Having read this I thought it was very informative. I appreciate you taking the time and effort to put this article together. I once again find myself spending way to much time both reading and commenting. But so what, it was still worth it!

  13. Great ?V I should certainly pronounce, impressed with your site. I had no trouble navigating through all the tabs and related info ended up being truly simple to do to access. I recently found what I hoped for before you know it in the least. Quite unusual. Is likely to appreciate it for those who add forums or something, website theme . a tones way for your client to communicate. Excellent task..

  14. Wonderful beat ! I wish to apprentice while you amend your site, how could i subscribe for a blog site? The account aided me a acceptable deal. I had been tiny bit acquainted of this your broadcast offered bright clear idea

  15. Hi there! This post couldn’t be written any better! Reading through this post reminds me of my previous room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thank you for sharing!

  16. I keep listening to the news update talk about receiving boundless online grant applications so I have been looking around for the most excellent site to get one. Could you advise me please, where could i find some?

  17. I’m still learning from you, while I’m improving myself. I definitely liked reading everything that is written on your site.Keep the information coming. I enjoyed it!

  18. wonderful post, very informative. I wonder why the other experts of this sector do not notice this. You should continue your writing. I am confident, you have a great readers’ base already!

  19. Thanks for the thoughts you are sharing on this weblog. Another thing I’d really like to say is getting hold of copies of your credit history in order to look at accuracy of each detail is one first measures you have to perform in credit restoration. You are looking to freshen your credit report from damaging details mistakes that ruin your credit score.

  20. Thank you for another informative site. Where else could I get that type of info written in such a perfect way? I have a project that I am just now working on, and I have been on the look out for such info.

  21. วิธีเล่น พี จีสล็อต 99 ไม่ยากเป็นเว็บไซต์การพนันที่เชี่ยวชาญในเกม PG SLOT ออนไลน์ ที่มีเกมสล็อตมากกว่า 300 เกมส์จากผู้ผลิตเกมส์ชั้นนำทั่วโลก มีระบบการเล่นเกมที่ง่ายและสะดวกสบาย

  22. Some are medicines that help people when doctors prescribe. Comprehensive side effect and adverse reaction information.

    https://prednisoned.top/ prednisone 10mg tablet cost
    safe and effective drugs are available. Read now.

  23. UK Victoria Rees, UK government introduces trade restrictions to reduce drug shortages, European Pharmaceutical Review, 3 October 2019 buy cialis online no prescription As expected, peripheral inhibition of CB1 signaling decreased the energy intake of Con mice, but did not significantly affect that of OGT FKO mice Fig

  24. Some are medicines that help people when doctors prescribe. Get warning information here.
    tadalafil 100mg
    Comprehensive side effect and adverse reaction information. What side effects can this medication cause?

  25. I’ve been looking for photos and articles on this topic over the past few days due to a school assignment, bitcoincasino and I’m really happy to find a post with the material I was looking for! I bookmark and will come often! Thanks 😀 KK

  26. Everything what you want to know about pills. drug information and news for professionals and consumers.
    ed meds
    All trends of medicament. Read now.

  27. earch our drug database. Comprehensive side effect and adverse reaction information.
    https://nexium.top/# how can i get cheap nexium without prescription
    Definitive journal of drugs and therapeutics. Cautions.

  28. The assignment submission period was over and I was nervous, slotsite and I am very happy to see your post just in time and it was a great help. Thank you ! Leave your blog address below. Please visit me anytime.

  29. Conclusion Data from the preventive IBIS I study did not support an association between the CYP2D6 phenotype and breast cancer outcome or the development of endocrine symptoms in tamoxifen treated women get viagra online It has, since the beginning of the Republic, been involved in this struggle

  30. Components that fit the content. I just stumbled upon your weblog and subscription capital and said I actually enjoy your weblog posts. I’ll subscribe to your augmentation anyway. Otherwise, even if I succeed, you can continue to enter quickly. https://totoilmi.com/

  31. I feel like I’m reading my mind! You seem to know too much about this book, as if you were writing a book. I think I can deliver a message with a few pictures. Instead, this is a nice blog. a fine reading I’ll be back for sure. https://totovi.com/

  32. Imagine for sure what you said. Your favorite justification seemed the simplest thing to consider on the Internet. I tell you, I’m certainly annoyed while people consider issues that they clearly do not recognise. You’ve nailed it to the top and defined everything with no side effects. People can get signals. Maybe come back to get more. Thank you. https://totoguy.com/

  33. I?¦ve been exploring for a bit for any high quality articles or weblog posts on this sort of area . Exploring in Yahoo I at last stumbled upon this site. Reading this info So i?¦m happy to exhibit that I’ve a very excellent uncanny feeling I came upon exactly what I needed. I so much unquestionably will make certain to don?¦t omit this site and provides it a glance on a constant basis.

  34. What i don’t understood is in fact how you are no longer really a lot more neatly-preferred than you may be right now. You’re so intelligent. You realize thus significantly relating to this subject, produced me in my view believe it from a lot of various angles. Its like men and women aren’t involved except it’s something to accomplish with Woman gaga! Your own stuffs excellent. Always take care of it up!

  35. 你知道澳门的百家乐赌桌数是全球之冠吗?起源自西欧,如今称霸亚洲赌场,特别受到中国赌客爱戴,让西方菠菜圈好奇不已,究竟百家乐何以大受中国人欢迎,小编与您一同解谜!详情请看: bit.ly 3cEWG8l Powered by 百家乐游戏 @2013-2022 RSS地图 HTML地图 百家乐走势软件是由多名百家乐技术爱好者为战胜真人百家乐而组成的团队,致力于研发最稳定的百家乐投注技术,开发最实用最科学的现场百家乐智能辅助软件。为百家乐爱好者提供最好的游戏辅导,合理分配管理娱乐资金,有效控制游戏心态,稳定提高玩家赢面。 Yes88娛樂城 基金产品缭乱复杂,如何挑选好基金?关注投基家后,投基君带你拨开云雾,研究分析合适你的基金,筛选出有道德的专业管理人,为你的基金投资组合保驾护航。 https://marcophxp542197.wizzardsblog.com/14380868/神-來-也-德州 长沙麻将,双豪华七小对怎么算?我来答 共1个回答 匿名用户 七小对庄家是7番,闲家是6番,双豪华庄家14番,闲家12番,鸟对鸟中俩鸟,倘为庄家就是14+7=21×4=84番,闲家是6+12=18×4 清一色的七小对,即全部都是万或筒或条的七小对是24番。如果全是风牌(东南西北中发白)的七小对,则是64番。七小对,国标麻将规则的番种,是基本胡牌型的一种,以七种对子成和。如果手中 广东麻将番型介绍广东麻将番数赢家赢分=牌局赢分(转自:wWw.CspEnGbo.com蓬勃范文网:【广东麻将番型介绍】广东麻将番数图解)X(抓中马数+1)+杠牌输赢输家输分=牌 四个人以上七个人以下只有一桌麻将,场上打牌的四个人中放铳了的牌手下去,另外一个替换上来,如果有一牌手自摸和牌,那么被替换的就是和牌牌手的对家。如此轮番上场打麻将的方式就

  36. Do you have a spam problem on this blog; I also am a blogger, and I was curious about your situation; many of us have created some nice practices and we are looking to swap solutions with other folks, be sure to shoot me an email if interested.