4

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

3
  • Do you require to have array instead of C-string pointer ? Doesn't const char* my_string; enough ? Commented Jul 27, 2016 at 17:31
  • 1
    BTW, std::cout << is not constexpr. Commented Jul 27, 2016 at 17:32
  • Put the variable in an anonymous namespace outside the function and use the BOOST_CONSTEXPR_OR_CONST cv on it. Commented Jul 27, 2016 at 17:53

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This confirms my suspicion that this is an unnecessary annoying restriction. For a single use, the suggestions are trivial changes, but this applies to dozens of functions and distributions so any change is messy. There are other impediments to making it constexpr, so I'll wait for a relaxation in c++latest.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.