【问题标题】:Transform any signed char type into an unsigned one将任何有符号字符类型转换为无符号字符
【发布时间】:2014-06-21 12:27:05
【问题描述】:
template< typename charT >
struct serializer
{
    /* ... */
private:
    std::basic_string< charT > base64_encode( unsigned charT * bytes, unsigned length );
};

我希望私有成员函数采用 unsigned 任何字符类型。如果 charT 是 char16_t、char32_t、wchar_t,我希望签名是 unsigned that。我该怎么做?

【问题讨论】:

    标签: c++ templates char wchar


    【解决方案1】:

    最简单的方法是使用std::make_unsigned,它适用于任何整数类型:

    template<typename T>
    typename std::make_unsigned<T>::type convert(T const& input)
    {
        return static_cast<typename std::make_unsigned<T>::type>(input);
    }
    

    在你的类中直接使用它会变得相当难看,所以我们将添加一个类型别名:

    template< typename charT >
    struct serializer
    {
        typedef typename ::std::make_unsigned<charT>::type ucharT;
        /* ... */
    private:
        std::basic_string< ucharT > base64_encode( ucharT * bytes, unsigned length );
    };
    

    【讨论】:

    • 函数签名中应该只有ucharT* bytes,没有unsigned - 因为ucharT类型现在已经无符号了。
    猜你喜欢
    • 2019-11-08
    • 2011-06-14
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    相关资源
    最近更新 更多