Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return type of decltype()

In the below code, why decltype(++c) returns int& instead of int whereas decltype(a++) return int.

#include <iostream>
#include <typeinfo>

int main()
{
    int32_t a {};
    decltype(a++) b; // OK

    int32_t c{};
    decltype(++c) d; // error: 'd' declared as reference but not initialized

    std::cout << "typeid(b) = " << typeid(b).name() << std::endl;
    std::cout << "typeid(d) = " << typeid(d).name() << std::endl;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The result of the built-in pre-increment operator is a lvalue referring to the operand (which then holds the value after the increment). This means that for example ++a = 1; is valid. The result of ++a refers to the variable a which can be assigned a value 1.

The result of the built-in post-increment operator is a prvalue of the previous value of the operand. (It couldn’t be a lvalue referring to the operand since post-increment is supposed to give the previous value before the increment.) This means that e.g. a++ = 1; is not valid since the result of a++ is not referring to a, but is just the original value of a and a value can’t be assigned a value.

decltype applied to a prvalue expression gives a non-reference. Applied to a lvalue expression it gives an lvalue reference to the expression’s type. This mimics the return types you would need to use to get the same value categories for the expressions if you overloaded the increment operators.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading