【发布时间】:2014-01-23 01:05:40
【问题描述】:
我正在编写一个模板类String(仅用于学习目的)并且有一个小问题。如果 T 是 wchar_t 而 U 是 char 并且反之亦然,那么我缺少什么让这种方法起作用?
template<typename U>
String<T> operator + (const U* other)
{
String<T> newString;
uint32_t otherLength = length(other);
uint32_t stringLength = m_length + otherLength;
uint32_t totalLength = stringLength * sizeof(T) + sizeof(T);
T *buffer = new T[totalLength];
memset(buffer, 0, totalLength);
memcpy(buffer, m_value, m_length * sizeof(T));
newString.m_value = buffer;
newString.m_length = stringLength;
memcpy(newString.m_value + m_length, other, otherLength * sizeof(T));
return newString;
}
好的,下面的 Jared 提出了一个解决方案,所以是这样的(有错误,我知道,只是一个模板)?
template<typename U>
String<T> operator + (const U* other)
{
String<T> newString;
uint32_t sizeOfT = sizeof(T); // wchar_t is 4
uint32_t sizeOfU = sizeof(U); // char is 1
T* convertedString;
int i = 0;
while (*other != 0)
{
convertedString[i] = ConvertChar(*other);
other++;
i++;
}
return newString;
}
template <typename U>
T ConvertChar(U character)
{
}
【问题讨论】:
-
如果你所有的字符都是 ASCII 字符,那么哑 wchar_t 到 char 是好的。在任何其他情况下,您需要将 Unicode 转换为 UTF8。 utfcpp.sourceforge.net