[cfe-dev] Constexpr and std::pair
Richard Smith
richard at metafoo.co.uk
Tue Feb 18 12:27:05 PST 2014
On Tue, Feb 18, 2014 at 12:03 PM, Marshall Clow <mclow.lists at gmail.com>wrote:
> Consider the following code:
>
> constexpr int x = 0;
> constexpr int y = 1;
> constexpr std::pair<const int &, const int &> p {x,y};
>
> Shouldn't that compile? (with -std=c++1y)
>
Depends. If this is namespace-scope, then yes. If it's block-scope, then no
(it should compile only if the addresses of x and y are constant).
> In C++14, we have:
> constexpr pair(const T1& x, const T2& y);
> (and yes, libc++ implements it that way).
>
> But clang rejects it, with:
> junk2.cpp:18:46: error: constexpr variable 'p' must be initialized by a
> constant
> expression
> constexpr std::pair<const int&, const int&> p { x, y };
> ^~~~~~~~
> junk2.cpp:18:46: note: reference to 'x' is not a constant expression
> junk2.cpp:15:16: note: declared here
> constexpr int x = 0;
>
> with the caret pointing at the 'p' in "> p { x, y };"
>
>
> Followup question. Assuming that this should compile, then what about this?
>
> typedef std::pair<const int &, const int &> p_t;
> constexpr int x = 0;
> constexpr int y = 1;
> constexpr p_t foo () { return p_t{x,y}; }
>
> constexpr p_t bar = foo();
>
> pair's copy and copy constructors are defined as "= default".
>
> But, 20.3.2/2 says:
>
> The defaulted move and copy constructor, respectively, of pair shall be a
> constexpr function if and only if all required element-wise initializations
> for copy and move, respectively, would satisfy the requirements for a
> constexpr function.
I think this should work (and indeed it seems to with libc++, but not with
libstdc++ where the pair move constructor is not constexpr).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20140218/a6e6bc0e/attachment.html>
More information about the cfe-dev
mailing list