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?
The decltype type specifier yields the type of a specified expression. The decltype type specifier, together with the auto keyword, is useful primarily to developers who write template libraries. Use auto and decltype to declare a template function whose return type depends on the types of its template arguments.
auto is a keyword in C++11 and later that is used for automatic type deduction. The decltype type specifier yields the type of a specified expression. Unlike auto that deduces types based on values being assigned to the variable, decltype deduces the type from an expression passed to it.
decltype returnsIf what we pass to decltype is the name of a variable (e.g. decltype(x) above) or function or denotes a member of an object ( decltype x.i ), then the result is the type of whatever this refers to. As the example of decltype(y) above shows, this includes reference, const and volatile specifiers.
decltype is a compile time evaluation (like sizeof ), and so can only use the static type.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With