I am trying to initialize a constexpr
reference with no success. I tried
#include <iostream>
constexpr int& f(int& x) // can define functions returning constexpr references
{
return x;
}
int main()
{
constexpr int x{20};
constexpr const int& z = x; // error here
}
but I'm getting a compile time error
error: constexpr variable 'z' must be initialized by a constant expression
Dropping the const
results in
error: binding of reference to type 'int' to a value of type 'const int' drops qualifiers
even though I had the feeling that constexpr
automatically implies const
for variable declarations.
So my questions are:
- Are
constexpr
references ever useful? (i.e., "better" thanconst
references) - If yes, how can I effectively define them?
PS: I've seen a couple of questions related to mine, such as Which values can be assigned to a `constexpr` reference? , but I don't think they address my questions.