Colet
Colet

Reputation: 495

string& vs. wstring& in runtime_error

I need my exception class, that inherits runtime_class, to accept wstring&. This is MyExceptions.h:

using namespace std;

class myExceptions : public runtime_error
{

public:
    myExceptions(const string &msg ) : runtime_error(msg){};
    ~myExceptions() throw(){};

};

I would like myExceptions to accept wstring& like this : myExceptions(const **wstring** &msg ). But when I run that, I got this error:

C2664: 'std::runtime_error(const std__string &): cannot convert parameter 1 from 'const std::wstring' to 'const std::string &'

I understand that runtime_error accepts string& and not wstring& as defined as following from C++ Reference - runtime_error:

> explicit runtime_error (const string& what_arg); 

How can I use wstring& with in runtime_error?

Upvotes: 5

Views: 3356

Answers (1)

Nicola Musatti
Nicola Musatti

Reputation: 18226

The easiest thing to do would be to pass to runtime_error a conventional message and handle your wstring message directly in your myExceptions class:

class myExceptions : public runtime_error {
public:
    myExceptions(const wstring &msg ) : runtime_error("Error!"), message(msg) {};
    ~myExceptions() throw(){};

    wstring get_message() { return message; }

private:
    wstring message;
};

Otherwise you could write a private static member function that converted from wstring to string and use it to pass the converted string to runtime_error's constructor. However, as you can see from this answer, it's not a very simple thing to do, possibly a bit too much for an exception constructor.

Upvotes: 3

Related Questions