Question

I am learning decltype in C++ 11.

The function of auto and decltype seems duplicated and I don't understand why we need decltype.

According to wiki, Its primary intended use is in generic programming, where it is often difficult, or even impossible, to express types that depend on template parameters.

In generic programming, I can use auto when it is difficult to express types:

template <typename T>
void MakeAnObject (const T& builder)
{
    auto val = builder.MakeObject();
    // do stuff with val
}

I don't understand why decltype is required.

Can decltype do something which auto can not?

Was it helpful?

Solution

auto means "the variable's type is deduced from the initialiser."

decltype refers to a type in an arbitrary context.

Here's an example where you can't use auto:

template <typename T, typename U, typename V>
void madd(const T &t, const U &u, const V &v, decltype(t * u + v) &res)
{
  res = t * u + v;
}

There is no initialiser in the parameter declaration (and there can't be), so you can't use auto there.

The thing is, 99% of uses for decltype is in templates. There's no equivalent functionality for it there. In non-template code, auto is usually what you want to use.

OTHER TIPS

While it is useful to get variables declared using auto, if you actually need to know the type of an expression, e.g., when producing a return type for a templatized function, auto isn't sufficient: you need to not just name a value but you need to get hold of type, e.g., to modify it. If anything could be dropped it would be auto. However, the use of decltype() tends to be a lot more wordy, i.e., auto is a nice short-cut.

auto is deduction of a type from an initializer.

Example:

auto x = 7; 
auto x = expression;

decltype[E] is the type ("declared type") of the name or expression E and can be used in declarations.

Example:

template <class T, class U>
auto mult(T& t1, U& u1) -> decltype (t1 * u1)
{
    return t1 * u1;
} 

Even the second case of auto can be replace by decltype but auto looks good for this.

decltype (j * i) m = j * i;

decltype is mostly used in template programming.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top