在constexpr函数中声明为静态的文字字符串 [英] literal string declared static in constexpr function

查看:327
本文介绍了在constexpr函数中声明为静态的文字字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使constexpr一些现有代码,但得到消息

I'm trying to make constexpr some existing code, but getting message

错误:在'constexpr'函数中'my_string'被声明为'static'

error: 'my_string' declared 'static' in 'constexpr' function

经过简化,代码为:

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来获得.)

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

推荐答案

当前在constexpr函数中不能包含静态变量.如果使用编译时表达式初始化变量,则有一个建议可以放宽该要求.

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.

由于您要分配给字符串文字,因此我建议仅删除静态",并假设编译器使任一种方式都使其尽可能最佳(实际上,应该这样做).另一种选择是使字符串成为static constexpr作为私有类成员,或在命名空间范围内.

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.

这篇关于在constexpr函数中声明为静态的文字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆