1

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.

Community
  • 1
  • 1
Marc.2377
  • 7,807
  • 7
  • 51
  • 95

1 Answers1

0

I don't think there is a widely acknowledged "best practice" for this scenario; either approach will work fine. Which one you choose should depend on whether you which code-quality you value more: performance (in which case inline can theoretically give you better performance, although perhaps not measurably better) or maintainability (in which case non-inline may give you more readable debugger output, and avoids the need to recompile most of your program if/when you change the implementation of either these two functions).

A (minor) usability advantage of the inline approach is seen if the functions are used by multiple projects; with the inline methods, the maintainer of each project won't need to remember to include the .cpp file in his project or Makefile. With the definition-in.cpp approach, OTOH, any project that calls those functions will get link errors if the .cpp file (or .a file or .so file) where the methods are defined isn't specified in his project.

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234