Using decltype to get an expression's type, without the const
Solution 1:
I prefer auto i = decltype(e){0};
for this. It's a bit simpler than using type_traits
, and I feel it more explicitly specifies the intent that you want a variable initialized to a 0 of e
's type.
I've been using Herb's "AAA Style" a lot lately, so it could just be bias on my part.
Solution 2:
Use std::remove_const
:
#include<type_traits>
...
for (std::remove_const<decltype(e)>::type i{0}; i < e; ++i)
Solution 3:
You can also use std::decay
:
#include<type_traits>
...
for (std::decay<decltype(e)>::type i{}; i < e; ++i) {
// do something
}
Solution 4:
A solution not mentioned yet:
for (decltype(+e) i{0}; i < e; ++i)
Prvalues of primitive type have const
stripped; so +e
is a prvalue of type int
and therefore decltype(+e)
is int
.