Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is decltype(std) legal, and does it have any purpose?

When using decltype around a namespace, I can write code that compiles, but the statement doesn't seem to have any effect under g++4.9.1, under clang it produces error: unexpected namespace name 'std': expected expression

For example, the following all compile under g++, but the assembly doesn't show any code generated for them.

using s = decltype(std);
auto n = typeid(decltype(std)).name();
auto sz = n.size();
std::printf("size is %zu\n", sz+1);
std::printf("this type is: %s\n\n", n.c_str());

// the only limit is your imagination
int f();
std::ostream trash = f(typeid(decltype(std)) * 10 - 6 ^ typeid(decltype(std)));

If g++ is right in allowing this? If so, what's the advantage of the code disappearing rather than causing a compile-time error?

like image 808
Ryan Haining Avatar asked Sep 30 '14 15:09

Ryan Haining


People also ask

What is the use of decltype?

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 function template whose return type depends on the types of its template arguments.

What is the difference between auto and decltype?

'auto' lets you declare a variable with a particular type whereas decltype lets you extract the type from the variable so decltype is sort of an operator that evaluates the type of passed expression.

Should I use decltype?

Another thing to consider is that decltype isn't really necessary unless you're writing library code, auto is nice for everyday programming if you want to make your code more concise, it's up for debate wether using as much auto as possible is good, but it's virtually necessary when working with unutterable types like ...

Is decltype runtime or compile time?

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


1 Answers

No, it's not legal. The two decltype-specifier forms that are allowed by the grammar are (N3690, §7.1.6.2/1):

decltype-specifier:
decltype ( expression )
decltype ( auto )

and a namespace name is not an expression.

The paragraph I quoted is from a standard draft post C++11, so decltype(auto) doesn't apply to C++11. The answer is the same, though.

like image 111
jrok Avatar answered Sep 30 '22 12:09

jrok