基于标准库实现string和wstring的转换

// convert string to wstring
std::wstring to_wstring(const std::string& str,
	const std::locale& loc = std::locale())
{
	std::vector<wchar_t> buf(str.size());
	std::use_facet<std::ctype<wchar_t>>(loc).widen(str.data(),//ctype<char_type>
		str.data() + str.size(),
		buf.data());//把char转换为T
	return std::wstring(buf.data(), buf.size());
}

// convert wstring to string with ’?’ as default character
std::string to_string(const std::wstring& str,
	const std::locale& loc = std::locale())
{
	std::vector<char> buf(str.size());
	std::use_facet<std::ctype<wchar_t>>(loc).narrow(str.data(),
		str.data() + str.size(),
		' ? ', buf.data());//把T转换为char
	return std::string(buf.data(), buf.size());
}


 

char c = 'a';
bool  bl = use_facet<ctype<char>>(locale("")).is(ctype_base::lower, c);

要比Convenience Functions std::islower(c,loc)效率高。

member type definition description
char_type The template parameter (charT) Character type
The class also inherits ctype_base::mask, which is used extensively as a parameter and return type by member functions (see ctype_base).
原文地址:https://www.cnblogs.com/ggzone/p/10121329.html