Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 867
TemplateRex Avatar asked Jan 12 '17 21:01

TemplateRex


1 Answers

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.

like image 57
Jonathan Wakely Avatar answered Oct 26 '22 07:10

Jonathan Wakely