【问题标题】:Converting from wchar_t a char and vice versa从 wchar_t 转换为 char,反之亦然
【发布时间】: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

标签: c++ encoding char wchar-t


【解决方案1】:

现在,当从 U* 转换为 String&lt;T&gt; 时,您的代码实际上是在使用内存副本。不幸的是,这不起作用,因为wchar_tchar 具有不同的内存布局。特别是 wchar_t 通常占用 2 个字节,而 char 是单个 byte。您需要在这里建立一个适当的转换函数,该函数应该应用于字符串中的每个项目

T ConvertChar(U c) { ... }

【讨论】:

  • 是的。除此之外 wchar_t char 转换不仅是每个元素的截断/扩展。如果您的语言环境是英语并且您仅在区间 [0, 256) 中使用 wchar_t
  • @Fallen 是的,这接近我的预期。但是现在您需要将其集成到循环中。您需要将该转换应用于源字符串中的每个字符,而不是执行 memcpy
【解决方案2】:

虽然从char 转换为wchar_t(即使用wchar_t(c))时可以扩大范围,但它可能做错了事。当从wchar_t 转换为char 时,很明显您可能会丢失信息。单个字符实体实际上表示单个字符,而实际上只是表示 UTF-8 或 UTF-16 的字节,这已变得很普遍。在这种情况下,可能需要将元素编码/解码为相应的其他表示。显然,转换不是一对一的:一些 Unicode 字符由多个 UTF-8 字节和多个 UTF-16 字组成。

您可能想看看 std::codecvt&lt;...&gt; 以了解编码之间的转换。

【讨论】:

    猜你喜欢
    • 2011-11-12
    • 2020-03-01
    • 2021-01-01
    • 1970-01-01
    • 2018-02-06
    • 2021-06-10
    • 2014-11-08
    • 1970-01-01
    • 2011-05-16
    相关资源
    最近更新 更多