下面的這段代碼如何從轉換std::string_view為std::string編譯:
struct S {
std::string str;
S(std::string_view str_view) : str{ str_view } { }
};
但這個不編譯?
void foo(std::string) { }
int main() {
std::string_view str_view{ "text" };
foo(str_view);
}
第二個給出錯誤:cannot convert argument 1 from std::string_view to std::string和no sutiable user-defined conversion from std::string_view to std::string exists。
我應該如何foo()正確呼叫?
uj5u.com熱心網友回復:
您嘗試呼叫的建構式是
// C 11-17
template< class T >
explicit basic_string( const T& t,
const Allocator& alloc = Allocator() );
// C 20
template< class T >
explicit constexpr basic_string( const T& t,
const Allocator& alloc = Allocator() );
如您所見,它被標記為explicit,這意味著不允許隱式轉換呼叫該建構式。
使用str{ str_view }字串視圖顯式初始化字串,因此是允許的。
由于foo(str_view)您依賴編譯器將 the 隱式轉換string_view為 a string,并且由于顯式建構式,您將收到編譯器錯誤。要修復它,您需要明確表示
foo(std::string{str_view});
uj5u.com熱心網友回復:
我應該如何正確呼叫 foo()?
像這樣:
foo(std::string{str_view});
下面這段從 std::string_view 轉換為 std::string 的代碼怎么可能編譯:
它是對 的顯式轉換std::string。它可以呼叫顯式轉換建構式。
但這個不編譯?
它是對 的隱式轉換std::string。它不能呼叫顯式轉換建構式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/336997.html
