I was looking for an appropriate way of converting wstring
to string
in C++, and found a nice one on this answer. Here's how I implemented it, within a file called convert.hpp, included in my project:
#include <string>
#include <codecvt>
inline std::wstring s2ws(const std::string& str)
{
typedef std::codecvt_utf8<wchar_t> convert_typeX;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.from_bytes(str);
}
inline std::string ws2s(const std::wstring& wstr)
{
typedef std::codecvt_utf8<wchar_t> convert_typeX;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.to_bytes(wstr);
}
Question: Should I keep all of the code inside the header file, as done above, or the right thing to do is to split it between a header file and a .cpp file, like so...
convert.hpp
#include <string>
#include <codecvt>
std::wstring s2ws(const std::string& str);
std::string ws2s(const std::wstring& wstr);
convert.cpp
std::wstring s2ws(const std::string& str)
{
typedef std::codecvt_utf8<wchar_t> convert_typeX;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.from_bytes(str);
}
std::string ws2s(const std::wstring& wstr)
{
typedef std::codecvt_utf8<wchar_t> convert_typeX;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.to_bytes(wstr);
}
I just wanted to know which is considered best practice in cases like this.