Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is expression inside decltype executed, or just being checked for validation?

By using Expression SFINAE, you can detect if some operator or operation is supported or not.

for example,

template <class T>
auto f(T& t, size_t n) -> decltype(t.reserve(n), void())
 { t.reserve(n); }

My question is that t.reserve(n) inside decltype get executed or not?

If yes, does that mean t.reserve(n) got executed twice, one inside decltype and the other one inside the function body?

If not, is it just checked for validation during compilation time? But why it is not executed, I thought all the expressions in the comma separated expression list will get executed.

like image 565
Allanqunzi Avatar asked Aug 26 '15 15:08

Allanqunzi


People also ask

Is decltype evaluated?

Like the sizeof operator, decltype 's operand is not evaluated.

What does decltype do in C++?

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.

Why to use decltype?

You should use decltype when you want a new variable with precisely the same type as the original variable. You should use auto when you want to assign the value of some expression to a new variable and you want or need its type to be deduced.


1 Answers

No, from [dcl.type.simple]:

The operand of the decltype specifier is an unevaluated operand (Clause 5).

which means, from [expr]:

In some contexts, unevaluated operands appear (5.2.8, 5.3.3, 5.3.7, 7.1.6.2). An unevaluated operand is not evaluated. An unevaluated operand is considered a full-expression.

So in this particular context, the purpose of decltype(t.reserve(n), void()) is to verify that t.reserve(n) is a valid expression. If it is, then the function is a viable overload whose return type is void, and reserve() will be called exactly once (in the function body). If it is not, then we have a substitution failure and the function is not a viable overload candidate.

like image 162
Barry Avatar answered Sep 25 '22 21:09

Barry