Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Types Impossible to Name

Tags:

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?

like image 270
kirakun Avatar asked Mar 05 '11 22:03

kirakun


1 Answers

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.

like image 113
Philip Potter Avatar answered Sep 27 '22 02:09

Philip Potter