[cfe-dev] Constexpr and std::pair

Marshall Clow mclow.lists at gmail.com
Tue Feb 18 12:03:51 PST 2014


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

— Marshall





More information about the cfe-dev mailing list