Advertisement
Rapptz

widen.cpp

Oct 11th, 2013
411
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. #include <string>
  2. #include <locale>
  3. #include <new>
  4.  
  5. template<typename From, typename To>
  6. struct widen {
  7. private:
  8.     std::locale loc;
  9.     const std::ctype<To>* t;
  10. public:
  11.     widen(const std::locale& loc = std::locale{}) noexcept: loc(loc), t(&std::use_facet<std::ctype<To>>(loc)) {}
  12.  
  13.     std::basic_string<To> operator()(const std::basic_string<From>& str) const noexcept {
  14.         const From* ptr = str.c_str();
  15.         To* buffer = new(std::nothrow) To[str.size()];
  16.         if(buffer == nullptr)
  17.             return {};
  18.         t->widen(ptr, ptr + str.size(), buffer);
  19.         return { buffer, str.size() };
  20.     }
  21. };
  22.  
  23. template<typename T>
  24. struct widen<T, T> {
  25.     widen() noexcept = default;
  26.     std::basic_string<T>& operator()(const std::basic_string<T>& str) const noexcept {
  27.         return str;
  28.     }
  29. };
  30.  
  31. #include <iostream>
  32.  
  33. int main() {
  34.     std::wcout << widen<char, wchar_t>{}("Hello");
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement