c++ - 在 constexpr 函数中声明为静态的文字字符串

标签 c++ string static literals constexpr

我正在尝试对一些现有代码进行 constexpr,但收到消息

错误:“my_string”在“constexpr”函数中声明为“static”

大大简化了,代码是:

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.";
  }
};

字符串当然在其他地方使用,我想确保它们永远不会重复(如此静态)(并且我想保持使用静态以与 constexpr 不存在的 C++03 兼容通过使用 BOOST_CONSTEXPR_OR_CONST 可用)。

最佳答案

目前您不能在 constexpr 函数中使用静态变量。如果变量是用编译时表达式初始化的,有人提议放宽该要求。

由于您要分配给字符串文字,所以我建议您只删除“静态”并假设编译器以任何一种方式使其尽可能最佳(在实践中它应该这样做)。另一种选择是使字符串成为私有(private)类成员或在命名空间范围内的 static constexpr

关于c++ - 在 constexpr 函数中声明为静态的文字字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38619259/

相关文章:

c++ - 存储字符串数组(const char* stringlist[3])

c++ - 将对象数组写入和读取到二进制文件?

python - python 2.7.5 中的 str() 与 repr() 函数

c++ - 字符指针(由 new 分配)

java - 在 Java 中使用 try-catch 从 JTextField 中捕获分数的字符串输入

C++ 从文件中读取

c++ - 如何将位置 n 的 QList 拆分为新的 QList

java - 为什么在 Java 中不重写静态方法?

python - Python 中的实例变量与类变量

java - Java 中的动态和静态绑定(bind)