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

半腔热情 提交于 2019-12-10 13:27:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!