由于程式(C )中的一些限制,我有一個案例,我將一個可選字串分配給一個字串變數,這給出了以下錯誤:
error: no match for ‘operator=’ ...
這段代碼是這樣的:
void blah(std::experimental::optional<std::string> foo, // more parameters)
{
std::string bar;
if(foo)
{
bar = foo; //error
}
// more code
}
嘗試:
我嘗試使用以下方法將型別轉換為匹配:
bar = static_cast<std::string>(foo);
最終顯示此錯誤:
error: no matching function for call to ‘std::basic_string<char>::basic_string(std::experimental::optional<std::basic_string<char> >&)’
我想知道:
- 有沒有辦法處理這種情況?
- 或者這是設計限制,我必須使用其他方法而不是將可選字串分配給普通字串?
uj5u.com熱心網友回復:
你有幾種方法:
-
/*const*/std::string bar = foo.value_or("some default value"); -
std::string bar; if (foo) { bar = *foo; } -
std::string bar; if (foo) { bar = foo.value(); }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/369577.html
上一篇:使用REGEX_SUBSTR獲取特定分隔符之前的所有字符
下一篇:連接字串的意外行為
