I have the following two classes to make appending string
s - and wstring
s respectively - easier:
#include <string>
#include <sstream>
class StringBuilder
{
public:
template <typename T>
StringBuilder& operator<<(const T& t)
{
this->stream << t;
return *this;
}
operator std::string() const;
private:
std::ostringstream stream;
};
StringBuilder::operator std::string() const
{
return this->stream.str();
}
class WStringBuilder
{
public:
template <typename T>
WStringBuilder& operator<<(const T& t)
{
this->stream << t;
return *this;
}
explicit operator std::wstring() const;
private:
std::wstringstream stream;
};
WStringBuilder::operator std::wstring() const
{
return this->stream.str();
}
Now, as you see, pretty much all of the code (except for the concrete string
and stringstream
types) is repeated, especially the operators.
The question is:
- Is there any way to reduce the duplicated code? I thought about a base class, templates and specialization, but the problem is I don't know how to determine the correct
stringstream
type depending on thestring
type then.
wstring
. It's a bad attempt at Unicode support, and should be phased out wherever possible. If you have to communicate with an API that takes it, convert it there. See utf8everywhere.org \$\endgroup\$