Search code examples
c++c++11autodecltype

'Copy' variable type from other variable


With the addition of the 'auto'-keyword in c++11, I was wondering if it was possible to 'copy' the type of another variable, or the return type of a function.

For instance, in this code:

unsigned short x;
[...] // x is initialized with some value
for(auto i=0;i<x;i++)
{
    [...]
}

i would be an int. Would it be possible to give i the same type as x, without manually declaring it as 'unsigned short'?

Basically, what I'm looking for is something like:

[...]
for(type(x) i=0;i<x;i++)
[...]

Solution

  • You're looking for decltype specifier, which is supported from c++11.

    Inspects the declared type of an entity or the type and value category of an expression.

    You could use it to declare with the same type of another variable,

    for(decltype(x) i=0;i<x;i++)
    

    or from the return type of a function.

    unsigned short f();
    //...
    for(decltype(f()) i=0;i<x;i++)