我正在尝试对一些现有代码进行 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/