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?
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.
'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.
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 ...
decltype is a compile time evaluation (like sizeof ), and so can only use the static type.
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.
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