How to convert wstring into string?

前端 未结 17 2263
北海茫月
北海茫月 2020-11-22 13:10

The question is how to convert wstring to string?

I have next example :

#include 
#include 

int main()
{
    std::wstr         


        
17条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 13:36

    In case anyone else is interested: I needed a class that could be used interchangeably wherever either a string or wstring was expected. The following class convertible_string, based on dk123's solution, can be initialized with either a string, char const*, wstring or wchar_t const* and can be assigned to by or implicitly converted to either a string or wstring (so can be passed into a functions that take either).

    class convertible_string
    {
    public:
        // default ctor
        convertible_string()
        {}
    
        /* conversion ctors */
        convertible_string(std::string const& value) : value_(value)
        {}
        convertible_string(char const* val_array) : value_(val_array)
        {}
        convertible_string(std::wstring const& wvalue) : value_(ws2s(wvalue))
        {}
        convertible_string(wchar_t const* wval_array) : value_(ws2s(std::wstring(wval_array)))
        {}
    
        /* assignment operators */
        convertible_string& operator=(std::string const& value)
        {
            value_ = value;
            return *this;
        }
        convertible_string& operator=(std::wstring const& wvalue)
        {
            value_ = ws2s(wvalue);
            return *this;
        }
    
        /* implicit conversion operators */
        operator std::string() const { return value_; }
        operator std::wstring() const { return s2ws(value_); }
    private:
        std::string value_;
    };
    

提交回复
热议问题