How can I use decltype to get a link type?

I am working on some code using decltype in CodeGear RAD Studio. I tried a naive solution that does not look like this:

int main(int, char**) { int i; int &ir = i; decltype((ir)) ir_clone = ir; } 

Of course, this does not compile: Internal compiler error. I rather suspect that there is nothing particularly wrong with this code, and there is a compiler error regarding reference expressions. (By the way, g ++ has no problems with the code and compiles it in order.) However, this does not help to solve the problem, since the platform is not negotiable.

If, above, I wrote

  decltype(ir) ir_clone = ir; /* No extra parens */ 

It compiles and works as expected. However, the problem does not end there, since it does not correctly calculate the constant from the environment. In particular:

 struct S { int i; } s; const S* p = &s; decltype(p->i) i0 = si; /* i0 is an int */ decltype((p->i)) i1 = si; /* i1 is a const int& */ 

If I do not use parens to make the argument an expression, I lose the constant of the argument I need.

Another tool I can use is simple templates, for example:

 template<class T> struct unref { typedef T type; } template<class T> struct unref<T&> { typedef T type; } 

This allows me to remove the reference part of the type using unref<int&>::type .

I can’t figure out how to put together all of these tools to get a successful expression for the type I need. For one of the things I need, I am working on a generic macro that does "foreach". (Yes, I know Boost does it better.) It should handle the following scenarios:

 (vector<int>) vi => vector<int> (vector<int>&)vir => vector<int> (const vector<int>) cvi => const vector<int> (const vector<int>&)cvir => const vector<int> (const P*) cp->vi => const vector<int> (P*) p->vi => vector<int> 

So far, my simple attempts have not been executed:

 unref<decltype(cp->vi)> /* is vector<int>, not what I need. */ unref<decltype((cp->vi))> /* is const vector<int>, which is right. */ unref<decltype(vir)> /* is vector<int>, which is right. */ unref<decltype((vir))> /* Internal Compiler Error, which is a headache. */ 

Any ideas that will help me on the right track? I hope there’s just something simple. Maybe I'm attacking the problem from the wrong angle.

+4
source share
2 answers

Try making another, more complex expression that will result in the same type you want, for example:

 decltype((void(), ir)) 

I could not tell you why he corrects this, but sometimes a different expression will do the trick.

+2
source

You can use std :: remove_reference (see http://en.cppreference.com/w/cpp/types/remove_reference ).

+1
source

Source: https://habr.com/ru/post/1339380/


All Articles