Adam Varhegyi
Adam Varhegyi

Reputation: 9894

Confusion about wcout and cout, wstring and string

I have a class which holds a single wstring. I have 2 printing functions one for ostream and one for wostream.

I must use them like this:

 MyClass<char> s;
 s.push_back( 'H' );
 s.push_back( 'i' );
 //Printing with ostream   
 s.print( std::cout );

 MyClass<wchar_t> w;
 w.push_back( L'C' );
 w.push_back( L'+' );
 //Printing with wostream
 w.print( std::wcout );

My problem is, i cannot make a function to work with ostream, here is my class:

template<typename T>
MyClass{

private:

std::wstring *data;

public:

void push_back(const T& t) {

    data->push_back(t);
}
    //Does not work
void print(std::ostream& out) const{

    out<<*data;  //Results in a compile error

}
    //Does work verry well
void print(std::wostream& out) const {
    out << *data;
}


};

How can i achive this?

P.S.: I know this is nonsense, but in fact this is in a school exam which i had last year. So i cannot change the standards. This is the task.

Upvotes: 1

Views: 863

Answers (2)

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

The problem is that you're storing a std::wstring regardless of whether the template type T is char or wchar_t. Instead, you want to use the template std::basic_string with the appropriate type:

std::basic_string<T> *data;

std::string is just a typedef for std::basic_string<char>, and std::wstring is just a typedef for std::basic_string<wchar_t>.

Similarly, std::ostream is just a typedef for std::basic_ostream<char>, and std::wostream is just a typedef for std::basic_ostream<wchar_t>, so you could have a single print function that takes a std::basic_ostream templated on the appropriate type.

Upvotes: 8

Mike Seymour
Mike Seymour

Reputation: 254421

Store the correct type of string

std::basic_string<T> data;

and overload for just the correct basic_ostream specialisation, not for both ostream and wostream:

void print(std::basic_ostream<T> & out) const {
    out << data;
}

(Also, storing the string itself rather than an uninitialised pointer will give better results).

Upvotes: 4

Related Questions