簡體   English   中英

constexpr函數返回字符串文字

[英]constexpr function returning string literal

返回整數文字副本的函數

int number()
{ return 1; }

可以使用關鍵字constexpr輕松轉換為普通的編譯時表達式。

constexpr int number()
{ return 1; }

但是,當涉及到字符串文字時,我會感到困惑。 通常的方法是返回一個指向const char的指針,指向字符串文字,

const char* hello()
{ return "hello world"; }

但我認為僅僅將“const”更改為constexpr並不是我想要的(作為獎勵,它還會產生編譯器警告,使用gcc 4.7.1 將不推薦的從字符串常量轉換為'char *'

constexpr char* hello()
{ return "hello world"; }

有沒有辦法以這樣的方式實現hello() ,在下面的例子中調用被一個常量表達式替換?

int main()
{
    std::cout << hello() << "\n";
    return 0;
}

constconstexpr不可互換的 ,在你的情況下,你不想刪除const但你想添加constexpr如下所示:

constexpr const char* hello()
{
  return "hello world";
}

刪除const時收到的警告是因為字符串文字array of n const chararray of n const char因此指向字符串文字的指針應該是* const char **但是在C中 字符串文字是char數組,即使嘗試修改它們是未定義的行為,它是為了向后兼容而保留的,但是被折舊以便應該避免。

強制constexpr評估:

constexpr const char * hi = hello();
std::cout << hi << std::endl;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM