Using decltype to get an expression's type, without the const

Jim Garrison picture Jim Garrison · Oct 7, 2013 · Viewed 11.5k times · Source

Consider the following program:

int main ()
{
    const int e = 10;

    for (decltype(e) i{0}; i < e; ++i) {
        // do something
    }
}

This fails to compile with clang (as well as gcc):

decltype.cpp:5:35: error: read-only variable is not assignable
    for (decltype(e) i{0}; i < e; ++i) {
                                  ^ ~

Basically, the compiler is assuming that i must be const, since e is.

Is there a way I can use decltype to get the type of e, but removing the const specifier?

Answer

zch picture zch · Oct 8, 2013

Use std::remove_const:

#include<type_traits>
...
for (std::remove_const<decltype(e)>::type i{0}; i < e; ++i)