2016-07-27 35 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++放鬆。 –