Skip to content

Instantly share code, notes, and snippets.

@phetdam
Last active December 4, 2022 00:45
Show Gist options
  • Save phetdam/36d2312e6bd652b7a8b58260f5368d86 to your computer and use it in GitHub Desktop.
Save phetdam/36d2312e6bd652b7a8b58260f5368d86 to your computer and use it in GitHub Desktop.
The C++11 way to convert from string to wstring and back
template <typename Codecvt = std::codecvt_utf8<wchar_t>>
inline std::wstring to_wstring(const std::string& s)
{
std::wstring_convert<Codecvt> conv;
return conv.from_bytes(s);
}
build
build_win
to_wstring
*.exe
*.ilk
*.pdb

GNU/Linux:

cmake -S . -B build && cmake --build build && ./to_wstring

Windows:

cmake -S . -B build_win -G Ninja && cmake --build build_win && .\to_wstring

cmake_minimum_required(VERSION 3.16)
project(
to_wstring
VERSION 0.1.0
DESCRIPTION
"The C++11 way to convert from string to wstring and back"
HOMEPAGE_URL
https://gist.github.com/phetdam/36d2312e6bd652b7a8b58260f5368d86
LANGUAGES CXX
)
# technically, <codecvt> is deprecated in C++17, but sadly there isn't a
# suitable standard library replacement for it yet
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(to_wstring to_wstring.cc)
set_property(
TARGET to_wstring
PROPERTY RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}
)
/**
* @file to_wstring.cc
* @author Derek Huang
* @brief The C++11 way to convert from string to wstring and back
* @copyright MIT License
*/
#include <codecvt>
#include <cstdlib>
#include <locale>
#include <iostream>
#include <memory>
namespace {
/**
* Return a `std::wstring` from a `std::string`.
*
* @tparam Codecvt `std::codecvt` facet, default `std::codecvt_utf8<wchar_t>`
*
* @param s `const std::string&` string to convert
*/
template <typename Codecvt = std::codecvt_utf8<wchar_t>>
inline std::wstring to_wstring(const std::string& s)
{
std::wstring_convert<Codecvt> conv;
return conv.from_bytes(s);
}
/**
* Return a `std::string` from a `std::wstring`.
*
* @tparam Codecvt `std::codecvt` facet, default `std::codecvt_utf8<wchar_t>`
*
* @param ws `const std::wstring&` wide string to convert
*/
template <typename Codecvt = std::codecvt_utf8<wchar_t>>
inline std::string from_wstring(const std::wstring& ws)
{
std::wstring_convert<Codecvt> conv;
return conv.to_bytes(ws);
}
} // namespace
#define PDGIST_MY_STRING "this is my string"
int main()
{
std::cout << "to_wstring(\"" PDGIST_MY_STRING "\") -- ";
if (to_wstring(PDGIST_MY_STRING) == L"" PDGIST_MY_STRING)
std::cout << "success\n";
else
std::cout << "failure\n";
std::cout << "to_string(L\"" PDGIST_MY_STRING "\") -- ";
if (from_wstring(L"" PDGIST_MY_STRING) == PDGIST_MY_STRING)
std::cout << "success" << std::endl;
else
std::cout << "failure" << std::endl;
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment