Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 484
Jim Garrison Avatar asked Oct 07 '13 21:10

Jim Garrison


People also ask

What does decltype do in C++?

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.

What is the difference between auto and decltype?

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.

What does decltype return?

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.

Is decltype runtime or compile time?

decltype is a compile time evaluation (like sizeof ), and so can only use the static type.


1 Answers

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.

like image 107
Casey Avatar answered Sep 19 '22 00:09

Casey