literal string declared static in constexpr function

懵懂的女人 提交于 2019-12-24 01:44:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!