While reading Wikipedia’s page on decltype, I was curious about the statement,
Its [decltype’s] primary intended use is in generic
programming, where it is often
difficult, or even impossible, to name
types that depend on template
parameters.
While I can understand the difficulty part of that statement, what is an example where there is a need to name a type that cannot be named under C++03?
EDIT: My point is that since everything in C++ has a declaration of types. Why would there ever be a case where it is impossible to name a type? Furthermore, aren’t trait classes designed to yield type informations? Could trait classes be an alternative to decltype?
The wikipedia page you link has a perfect example:
Note that
foo(int&)returnsint&(a reference type) whilefoo(float&)returnsfloat(a nonreference type). Withoutdecltype, it’s impossible within the template to specify a type which represents “the return type of the functionfoowhich takes an argumenttof typeT“.In this example, it’s not a particular concrete type which is impossible to express — either
int&orfloatare individually expressible — but a higher level generic class of types.EDIT: and to answer your comment to another answer, this example is inexpressible in C++03. You cannot have a function template which will wrap any function
T1 foo(T2)and match both argument and return type of the wrapped function.