lundi 26 mars 2018

decltype without any variable type

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;

Aucun commentaire:

Enregistrer un commentaire