将std :: string_view传递给API,执行const std :: string&

问题描述 投票:0回答:1

我正在使用Socket.IO库来创建一个客户端。在发送消息时,我必须将我的消息(数据)作为sio::message::list(msg)传递

void Socket_IO::send_message(std::string_view msg)      //Gives Error
//void Socket_IO::send_message(const std::string &msg)  //Works
{
    this->client.socket()->emit(Socket_IO::general_message, sio::message::list(msg), [&](sio::message::list const& msg) {
    });
}

class sio :: message :: list有一个构造函数

list(const string& text)
{
    m_vector.push_back(string_message::create(text));
}

但是没有std :: string_view构造函数

错误:

'<function-style-cast>': cannot convert from 'std::string_view' to 'sio::message::list'

我想知道他们是否可以通过std :: string_view为API期望const std :: string&

我不能使用c_str()函数,因为字符串可能包含可能包含空字符(0x00)的二进制数据。

我正在考虑创建一个字符串对象sio::message::list(std::string str(msg)),但希望查询它会破坏使用std :: string_view的目的。

c++ std c++17 stdstring
1个回答
1
投票

你可以选择:

this->client.socket()->emit(Socket_IO::general_message, sio::message::list(std::string(msg)), ...

这使得工作完成了。它将初始化临时字符串对象并将其传递给列表构造函数。

© www.soinside.com 2019 - 2024. All rights reserved.