C++11: The decltype specifier – Part IAs C++ templates and generic programming become popular, programmers find it sometimes difficult to express the type for a variable or function. People are in urgent need of a mechanism to automatically deduce types for expressions. This new programming mechanism didn't appear until the appearance of decltype. Decltype solves the problem through getting the type or derived type of an expression and acting as the type specifier of another expression whose type needs to be deduced. Here is an example: int i; decltype (i) j = 1; In this example, decltype(i) gets the type of i, which is int. decltype(i) is the type specifier of variable j, so the type of j is also int. In some scenarios, decltype can improve the readability and maintainability of programs. See the following example: vector<int> vec;
for (vec { ... } With decltype, the program can be rewritten as follows: vector<int> vec;
typedef decl for (vectype i = vec.begin(); i < vec.end(); i++) { ... }
In this example, we use the combination of typedef and decltype to make vectype equivalent to vector<int>:: iterator. If vect
Decltype and templatesWe can use decltype in templates to further improve the generic capabilities of templates. For example: template<typename T, typename U> void sum(T t, U u, decltype(t+u) & s){ s= t+u; } int main(){ char var1 = 1; int var2 = 2; float var3= 1.0; double var4 = 2.5; int var5; double var6; sum(var1, var2, var5); // decltype(t+u) is int sum(var3, var4, var6); // decltype(t+u) is double } In this example, decltype(t+u) is not determined until the template instantation. With decltype, we don't need to specify the type of “t+u” in the template definition. However, a limitation is that users must decide the type of “t+u” in the template instantiation. We can use trailing return types to do further improvement for this program. One consideration is that if “t+u” is not a valid expression during the template instantiation; for example, t and u are arrays, the compiler will issue an error message. To avoid such kind of error, you need to provide other sum functions to support the add operation. The rules of decltype type deducing will be introduced in C++11: The decltype specifier – part II.
|