I am not so experienced with decltype usage in C++. However below is code which I finally arrived for my project purpose:
#include <iostream>
#include <inttypes.h>
#define SA(obj) ((obj)->u)
struct A
{
A()
{
std::cout << "Called" << std::flush << std::endl;
}
uint32_t u;
};
int main()
{
struct A a2;
decltype(A().u) p;
a2.u = 99;
p = a2.u;
if(a2.u != SA(&a2) )
std::cout << "Not Same" << std::flush << std::endl;
else
std::cout << "Same" << std::flush << std::endl;
}
I can see that the A's constructor is called only once cause of below statement:
struct A a2;
In same concern what does the construct in decltype means - will it not be creating a temporary instance of the structure -
decltype(A().u) p;
as the below declaration gives compilation error:
decltype(A.u) p;
c++ -std=c++11 try5.cpp
try5.cpp: In function 'int main()':
try5.cpp:18:17: error: invalid type in declaration before ';' token
decltype(A.u) p;
The expression inside decltype
's parentheses is not evaluated . It is just analyzed by the compiler to discover its type, but never translated into actual executable code.
Au
fails the analyzing stage, because you can't use .
after a type name.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.