问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/32231075/is-expression-inside-decltype-executed-or-just-being-checked-for-validation