简体   繁体   中英

Passing std::string_view to API execting const std::string&

I am using Socket.IO library to create a client. While sending a message I have to pass my message (data) as 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 has a constructor

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

but does not have a std::string_view constructor

Error :

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

I wish to know is their any way I can pass std::string_view for API expecting const std::string&

I can't use c_str() function as the string might contain binary data which may contain null character (0x00).

I was thinking of creating a string object sio::message::list(std::string str(msg)) but wish to inquire will it defeat the purpose of using std::string_view.

You could go with:

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

this makes the job done. It will initialize temporary string object and pass it to list constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM