Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

c++ - Why can't decomposition declarations be constexpr?

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").

question from:https://stackoverflow.com/questions/41622896/why-cant-decomposition-declarations-be-constexpr

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...