簡體   English   中英

c ++ 14中std :: string的運算符后綴

[英]operator suffix for std::string in c++14

我安裝了Clang 3.4,並為字符串文字“”s測試后綴運算符。

#include <string>

//1. using namespace std; // without compile error.
//2. using std::operator ""s; // or without it compile error, too.
// for success compiles, need 1. or 2. line.

int main()
{
    auto s = "hello world"s; 
}

如果我評論1和2,我得到編譯錯誤。 但我知道在大項目中1.方法很糟糕,2.方法很陌生。

問:我可以使用運算符“”而無需using namespace stdusing std::operator ""s進行任何編寫嗎?

結束評論:

你必須明確地using這些運算符。 這是標准的意圖。 你應該考慮只提供你需要的東西

using namespace std::literals;

要么

using namespace std::literals::string_literals;

根據您的需要,后者在有疑問的情況下更可取(僅拉動您需要的東西,而不是更多)。 與所有使用聲明或指令一樣,您希望將它們限制在實際的最小范圍內。

需要明確提取運算符的原因是后綴可能會在未來的擴展中在不同的上下文中重用。

如果您發現第二個選項很奇怪,這實際上很常見,您可以限制“using namespace std”的范圍,如下所示:

int main()
{
    using namespace std;
    auto s = "hello world"s; 
}

暫無
暫無

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

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