Clarification of decltype output when multiplying 2 const ints

int main() { const int a = 1; const int b = 2; typedef decltype(a*b) multiply_type; cout << typeid(multiply_type).name() << endl; return 0; } 

The return value of the program is that multiply_type is an int. I'm very surprised. I expected the deduction type to give const int, and since the expression gives the value pr, the resulting type will be const int.

PS: with auto, the return value will be int when it discards the const qualifier.

Any ideas why multiply_type is int instead of const int with decltype?

Edit: Added an example of addition, which is also associated with the cv qualifier.

 #include<iostream> #include<typeinfo> using namespace std; struct Details { int m_age; }; int main() { const Details* detail = new Details(); typedef decltype((detail->m_age)) age_type; cout << typeid(age_type).name() << endl; int a = 1; age_type age = a; age = 10; // This is not possible. Read only. cout << typeid(age).name() << endl; // This returns the type as int though. Then why is 20 not possble ? return 0; } 

Edit 2: Check out our link. http://thbecker.net/articles/auto_and_decltype/section_07.html `

 int x; const int& crx = x; / The type of (cx) is const int. Since (cx) is an lvalue, // decltype adds a reference to that: cx_with_parens_type // is const int&. typedef decltype((cx)) cx_with_parens_type;` 
+5
source share
1 answer

decltype evaluate the argument as is, decltype(i) , where i has a cv-qualification of lvalue, leads to a declaration of type cv-qual, but the expression i*i in decltype(i*i) creates an un materialized prvalue value of type i with non- cv-qualified, prvalue do not have an explicit idea of โ€‹โ€‹constness. your code will look like this:

 using T = const int; static_assert(is_same<int, decltype(0)>(), "Failed"); 

The fact that typeid does not show cv qualifications is that they are ignored:

5.2.8.5 - If the type of the expression or type identifier is a class with qualification cv, the result of the expression of type type refers to the std :: type_info object representing the cv-unqualified type.

+1
source

All Articles