decltype brief introduction

We used typeid Operator to query the type of a variable , This type of query is done at run time .RTTI The mechanism generates one for each type type_info Data of type , and typeid The variables returned by the query correspond to type_info data , adopt name The name of the member function return type . At the same time C++11 in typeid It also provides hash_code This member function , Unique hash value for return type .RTTI It can lead to lower runtime efficiency , And in generic programming , What we need more is to determine the type at compile time ,RTTI It can't meet such a requirement . Compiler - time type derivation is just for generic programming , In non generic programming , Our type is certain , There's no need to deduce at all .

And compile time type derivation , Apart from what we said auto keyword , And what's in this article decltype.

decltype And auto Same keyword , For compile time type derivation , But it has something to do with auto There are still some differences .decltype The type derivation of is not like auto The same is to get the type of the variable from the initialization expression of the variable declaration , But always Take a normal expression as an argument , Returns the type of the expression , and decltype The expression is not evaluated .

decltype usage

Derive expression types

 int i = 4;
decltype(i) a; // The results are as follows int.a The type of int.

And using/typedef share , Used to define a type .

 using size_t = decltype(sizeof(0));//sizeof(a) The return value of is size_t type 
using ptrdiff_t = decltype((int*)0 - (int*)0);
using nullptr_t = decltype(nullptr);
 vector<int >vec;
typedef decltype(vec.begin()) vectype;
for (vectype i = vec.begin; i != vec.end(); i++)
{
//...
}

And so auto equally , It also improves the readability of the code .

Reuse anonymous types

stay C++ in , We sometimes come across anonymous types , Such as :

struct
{
int d ;
doubel b;
}anon_s;

And with the help of decltype, We can reuse this anonymous structure :

decltype(anon_s) as ;// Defines an anonymous structure above 

In generic programming, we combine auto, The return value type used to trace functions

This is also decltype The biggest use .

template <typename _Tx, typename _Ty>
auto multiply(_Tx x, _Ty y)->decltype(_Tx*_Ty)
{
return x*y;
}

decltype Four rules of derivation

  1. If e Is a tag expression without parentheses or a class member access expression , So decltype(e) Namely e The type of named entity . Besides , If e Is an overloaded function , Will result in compilation errors .
  2. otherwise , hypothesis e The type is T, If e It's a dying value , that decltype(e) by T&&
  3. otherwise , hypothesis e The type is T, If e It's a left value , that decltype(e) by T&.
  4. otherwise , hypothesis e The type is T, be decltype(e) by T.

The tag refers to the removal of the keyword 、 Literal quantity and other tags that the compiler needs to use are defined by the programmer himself , The expression corresponding to a single marker is the marker expression . for example :

int arr[4]

be arr Is a marker expression , and arr[3]+0 No .

Let's look at the following code :

 int i=10;
decltype(i) a; //a Derived as int
decltype((i))b=i;//b Derived as int&, It must be initialized with , Otherwise, compilation error

Just for i Combined with the (), This leads to a difference in the results of type derivation . This is because ,i Is a marker expression , According to the rules of derivation 1, The type is derived as int. and (i) Is an lvalue expression , So the type is derived as int&.

You can learn more about the four rules of derivation through the following code

 int i = 4;
int arr[5] = { 0 };
int *ptr = arr;
struct S{ double d; }s ;
void Overloaded(int);
void Overloaded(char);// Overloaded functions
int && RvalRef();
const bool Func(int); // Rule one : Derived as its type
decltype (arr) var1; //int Marker expressions decltype (ptr) var2;//int * Marker expressions decltype(s.d) var3;//doubel Member access expression //decltype(Overloaded) var4;// overloaded function . Compile error . // Rule 2 : Dead value . Derived as a right valued reference to a type . decltype (RvalRef()) var5 = 1; // Rule three : The left value , Derived as a reference to a type . decltype ((i))var6 = i; //int& decltype (true ? i : i) var7 = i; //int& A conditional expression returns an lvalue . decltype (++i) var8 = i; //int& ++i return i Left value of . decltype(arr[5]) var9 = i;//int&. [] The operation returns an lvalue decltype(*ptr)var10 = i;//int& * The operation returns an lvalue decltype("hello")var11 = "hello"; //const char(&)[9] Literal constants of strings are left values , And for const The left value . // Rule 4 : None of the above , Then we deduce it as this type decltype(1) var12;//const int decltype(Func(1)) var13=true;//const bool decltype(i++) var14 = i;//int i++ Return right value

The tip here is , A string literal constant is an lvalue , And is const The left value , A non string literal constant is a right value .
So many rules , It's hard to remember for us to write code , Especially rule three . We can use C++11 Template classes added to the standard library is_lvalue_reference To determine whether the expression is an lvalue :

 cout << is_lvalue_reference<decltype(++i)>::value << endl;

result 1 Expressed as an lvalue , The result is 0 Is not a right value .
alike , Also have is_rvalue_reference Such a template class to judge decltype Infer whether the result is a right value .

Reference material :《 In depth understanding of C++11》

C++11 characteristic :decltype More articles about keywords

  1. C++11 Of decltype keyword

    C++11 Of decltype keyword summary decltype Key words and auto There are similarities and differences Sometimes we want to infer the type of variable to be defined from the type of expression , But you don't want to initialize variables with the value of the expression ( Use... If you want to initialize auto 了 ...

  2. C++ Developers should use 10 individual C++11 characteristic

    Reprinted from http://blog.jobbole.com/44015/ stay C++11 In the new standard , The language itself and the standard library have added a lot of new content , This article only deals with some fur . But I believe some of these new features , Should be everything C++ open ...

  3. 【 translate 】C++ What engineers need to master 10 individual C++11 characteristic

    Original title :Ten C++11 Features Every C++ Developer Should Use Original author :Marius Bancila Original address :codeproject remarks : Non literal translation , belt ...

  4. Reprint : Every C++ Ten that developers should use C++11 characteristic

    This article discusses a series of things that all developers should learn and use C++11 characteristic , In the new C++ In the standard , Many new properties have been added to both the language and the standard library , This article will just cover a few things , However , I believe that there are some characteristic usages that should become C++ Everyday usage of developers ...

  5. C++ Developers should use 10 individual C++11 characteristic turn

    http://blog.jobbole.com/44015/// | classification : C/C++, Development | comments | label : C++, C Language Share the : This paper is written by Bole Online - I'm not a vet if I can't cure you Translated from ...

  6. Developers should use 10 individual C++11 characteristic

    Abstract : stay C++11 In the new standard , The language itself and the standard library have added a lot of new content , This article only deals with some fur . But I believe some of these new features , Should be everything C++ Developer's general equipment . You may have seen many similar introductions C++11 Characteristic ...

  7. c++11 Feature learning summary

    ubuntu 16.04 Bring their own gcc 5.4 Support c++11 ubuntu 18.04 Bring their own gcc 7.3 Support c++14 Check compiler support : c++11 c++14 c++17 c++11 featu ...

  8. c++11 characteristic

    0. brief introduction stay c++11 In the standard , The language itself and the standard library have added a lot of new content . Some of the features in it , It will make you more elegant when you write code . My environment : System : ubuntu16.04 g++ edition : g++5.4.0 Use c ...

  9. c++11——auto,decltype Type derivation

    c++11 Introduced in auto and decltype Keyword implementation type derivation , Through these two keywords, we can not only easily obtain complex types , And it can simplify writing , Improve coding efficiency .     auto and decltype All type derivation is done by the compiler in ...

  10. C++11 in decltype Use

    The decltype type specifier yields the type of a specified expression. The decltype type specifier, ...

Random recommendation

  1. 【 Security testing 】sqlmap Installation method

    Reference material :http://jingyan.baidu.com/article/60ccbceb64cc2064cbb19748.html SQLMap It's using Python Written language , So we need to Python this ...

  2. 【JPA】 Two different implementations jpa Configuration method of

    Two different implementations jpa Configuration method of The first one is : com.mchange.v2.c3p0.ComboPooledDataSource datasource.connection.driver_class=co ...

  3. utilize FFT The discrete analytic signal is generated by calculation

    Usually the signals we use are real valued signals , But we can construct a complex signal from this real signal , So that the complex signal contains only the positive frequency part , And the real part of this complex signal is exactly our original real value signal . A simple deduction shows that , The imaginary part of the complex signal is the Hilbert of the original signal ...

  4. 【 turn 】Python Implement modification Windows CMD Command line output color ( Complete resolution )

    use Python When writing command line programs , Single output color is too monotonous . In fact, we can add some colors , For example, red for warning , Green means the result is normal, etc . There are several similar posts on the Internet , But I didn't make it clear , The code is not very clear . here , Yes Win ...

  5. PHP Simple HTML DOM Getting started with parser

    http://www.cnphp.info/php-simple-html-dom-parser-intro.html It's been used all the time php analysis html Document trees are a problem .Simple HTML DOM ...

  6. 「NOI2013」 Small Q The cultivation of Problem solving report

    「NOI2013」 Small Q The cultivation of Make a complete answer for the first time , It took half a night + One morning + Half an afternoon Overall, it's too slow For this question , I think the difficulty is to observe the data and guess the nature and read in operation I think about this every second sb How does a string read ...

  7. Scikit-learn skill ( expand ) summary

    Scikit-learn skill ( expand ) summary Reprinted from :http://www.jianshu.com/p/516f009c0875 Recently saw <Python Introduction and practice of data mining >, There is a place on the Internet to translate ...

  8. shell Typical cases of operation --FTP operation

    from FTP Download files from the server or upload files to FTP Server is one of the more common scenarios in the production environment . shell operation FTP The way to do this is as follows : Train of thought : Use shell call ftp Such as the client Use FTP The way , adopt shell call ft ...

  9. stay Arch gnome Install some software in

    One . stay Arch gnome Add ibus Chinese input method 1. install ibus-libpinyin. sudo pacman -S ibus-libpinyin If the system has not been installed before ibus, First through pac ...

  10. ArcGIS Desktop and Engine Middle to point feature layer Graduated Symbols Rendering implementation Rotation Symbol ( turn )

    Abstract         ArcGIS in , For the rendering of feature layers , Support to render the size of the feature according to the value of the feature field , among Graduated Symbols Size can be rendered hierarchically . In the process of personal development system , It can also be used to beautify the data display ...