USING THE DECLTYPE OPERATOR

You use the decltype operator to obtain the type of an expression, so decltype(exp) is the type of the value that results from evaluating the expression exp. For example, you could write the following statements:

double x(100.0);
int n(5);
decltype(x*n) result(x*n);

The last statement specifies the type of result to be the type of the expression x*n, which is type double. While this shows the mechanics of what the decltype operator does, the primary use for the decltype operator is in defining function templates. Occasionally, the return type of a template function with multiple type parameters may depend on the types used to instantiate the template. Suppose you want to write a template function to multiply corresponding elements of two arrays, possibly of different types, and return the sum of these products. Because the types of the two arrays may be different, the type of the result will depend on the actual types of the array arguments, so you cannot specify a particular return type. The function template might notionally look like this:

template<class T1, class T2>
return_type f(T1 v1[], T2 v2[], const size_t& count)
{
  decltype(v1[0]*v2[0]) sum(0);
  for(size_t i = 0; i<count; i++) sum += v1[i]*v2[i];
  return sum;
}

return_type needs to be the type of the result of multiplying corresponding elements of the array arguments. The decltype operator can help, but unfortunately the following will not compile:

template<class T1, class T2> decltype(v1[0]*v2[0]) ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.