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:
int& foo(int& i);
float foo(float& f);
template <class T> auto transparent_forwarder(T& t) −> decltype(foo(t)) {
return foo(t);
}
Note that foo(int&)
returns int&
(a reference type) while foo(float&)
returns float
(a nonreference type). Without decltype
, it's impossible within the template to specify a type which represents "the return type of the function foo
which takes an argument t
of type T
".
In this example, it's not a particular concrete type which is impossible to express -- either int&
or float
are 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.
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