Why can't decomposition declarations be constexpr?

余生长醉 提交于 2019-12-05 08:27:13

问题


Consider the following snippet to test the upcoming C++17 feature decomposition declarations (formerly known as structured bindings)

#include <cassert>
#include <utility>

constexpr auto divmod(int n, int d)
{
    return std::make_pair(n / d, n % d); // in g++7, also just std::pair{n/d, n%d}
}

int main()
{
    constexpr auto [q, r] = divmod(10, 3);
    static_assert(q == 3 && r ==1);
}

This fails on both g++7-SVN and clang-4.0-SVN with the message:

decomposition declaration cannot be declared 'constexpr'

Dropping the constexpr definition and changing to a regular assert() works on both compilers.

None of the WG21 papers on this feature mention the constexpr keyword, neither in the positive nor the negative.

Question: why aren't decomposition declarations be allowed to be constexpr? (apart from "because the Standard says so").


回答1:


Question: why aren't decomposition declarations be allowed to be constexpr? (apart from "because the Standard says so").

There is no other reason. The standard says in [dcl.dcl] p8:

The decl-specifier-seq shall contain only the type-specifier auto (7.1.7.4) and cv-qualifiers.

That means it can't be declared with constexpr.

This was the subject of a National Body comment on the C++17 CD, see US-95 in P0488R0:

Comment: There is no obvious reason why decomposition declarations cannot be declared as static, thread_local, or constexpr.
Proposed change: Allow constexpr, static, and thread_local to the permitted set of decl-specifiers.

Comments GB 16 and GB 17 are also related.

These comment were rejected for C++17 after review by the Evolution Working Group at the Nov 2016 meeting. It was unclear what some storage classes would mean on a structured binding declaration, and exactly how to change the specification to allow constexpr (simply allowing it in the grammar wouldn't say what it means). A paper exploring the design space was requested. It should be possible to change this in future without breaking any code, but there wasn't time to do it for C++17.



来源:https://stackoverflow.com/questions/41622896/why-cant-decomposition-declarations-be-constexpr

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