问题
I'm trying to make constexpr some existing code, but getting message
error: 'my_string' declared 'static' in 'constexpr' function
Much simplified, the code is:
template <typename T>
constexpr
int foo(const int x)
{
static // error: 'my_string' declared 'static' in 'constexpr' function
constexpr char my_string[] = "my foo error message!";
if (x == 0)
{
std::cout << my_string << std::endl;
}
return x;
}
class boo
{
public:
constexpr boo()
{
static // error: 'constructor_string' declared 'static' in 'constexpr' function
constexpr char constructor_string[] = "my constructor error message.";
}
};
The strings are used elsewhere of course and I'd like to ensure that they are never duplicated (so static) (and I'd like to maintain the use of static for compatibility with C++03 where the constexpr is not available by using BOOST_CONSTEXPR_OR_CONST).
回答1:
You can't have static variables in constexpr functions currently. There is a proposal to relax that requirement if the variable is initialized with a compile time expression.
Since you're assigning to a string literal, I would recommend just dropping the 'static' and assuming the compiler makes it as optimal as possible either way (which it should for this, in practice). Another option would be to make the string a static constexpr
as a private class member, or in namespace scope.
来源:https://stackoverflow.com/questions/38619259/literal-string-declared-static-in-constexpr-function