Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why decltype is required in C++11?

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?

like image 641
Kenny Lee Avatar asked Sep 16 '13 15:09

Kenny Lee


People also ask

What is the use of decltype?

The decltype type specifier yields the type of a specified expression. The decltype type specifier, together with the auto keyword, is useful primarily to developers who write template libraries. Use auto and decltype to declare a function template whose return type depends on the types of its template arguments.

What does decltype stand for?

Decltype keyword in C++ Decltype stands for declared type of an entity or the type of an expression. It lets you extract the type from the variable so decltype is sort of an operator that evaluates the type of passed expression. SYNTAX : decltype( expression )

Is decltype runtime or compile time?

decltype is a compile time evaluation (like sizeof ), and so can only use the static type.

How does decltype work in C++?

Decltype gives the type information at compile time while typeid gives at runtime. So, if we have a base class reference (or pointer) referring to (or pointing to) a derived class object, the decltype would give type as base class reference (or pointer, but typeid would give the derived type reference (or pointer).


1 Answers

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.

like image 117
Angew is no longer proud of SO Avatar answered Sep 28 '22 18:09

Angew is no longer proud of SO