2016-07-27 74 views
1

我试图让constexpr一些现有的代码,但得到的消息文字串宣布constexpr功能

错误静:“my_string”宣布“constexpr”静态'功能

大大简化,在代码:

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

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

+0

您是否需要使用数组而不是C字符串指针? 'const char * my_string'不够'? – Jarod42

+1

顺便说一下,'std :: cout <<'不是'constexpr'。 – Jarod42

+0

将变量放入函数外部的匿名名称空间中,并对其使用BOOST_CONSTEXPR_OR_CONST cv。 – kfsone

回答

1

当前不能在constexpr函数中使用静态变量。如果变量是用编译时表达式初始化的,有一个建议是放宽这个要求。因为你在分配字符串文字,所以我建议只删除'静态',并假设编译器尽可能以最优方式(实际上它应该这样做)最优化。另一种选择是将字符串static constexpr作为私有类成员或命名空间范围。

+0

这证实了我的怀疑,这是一个不必要的恼人的限制。对于一次性使用,这些建议是微不足道的变化,但这适用于数十种功能和分布,所以任何变化都很麻烦。还有其他的障碍让它更好,所以我会等待最新的C++放松。 –