如何使用&lt;&lt;输出unsigned / signed char或<cstdint>类型作为整数在C ++中</cstdint>

时间:2010-10-29 07:48:40

标签: c++ templates operator-overloading char cstdint

背景:

我有模板流操作符(例如operator << (ostream &, std::vector <T>))(输出容器元素可能是某些8位整数类型,(例如unsigned charint_least8_t等等)

问题:

默认是这些类型输出为char(ASCII)。 我只使用char(或wchar_t或其他)来表示ASCII变量,而不使用unsigned / signed类型。 如何将这些其他8位类型始终输出为signed int / unsigned int(数字),即使调用者不知道类型?

首先尝试:

我已经尝试过(使用GCC),例如定义operator << (ostream &, unsigned char)并使用其中的强制转换(即stream << static_cast <int> (value)。这适用于unsigned char值,但uint8_t仍然有效输出为char

相同的基础类型(即unsigned/signed char不能在重载中使用,因此我无法定义例如operator << (ostream &, int_fast8_t)的重载。

5 个答案:

答案 0 :(得分:3)

您将变量中保存的实际数据与您选择用于打印它的任何表示混淆。

以这种方式思考:charsintsdoubleslongs,whatevers,它们只是你存储数字的大块内存。 char是0到255之间的数字(或-128和127) - 您可以选择将其表示为ASCII字符,数字,或借助OpenGL将其表示为天空中的星号。

如果你想看到字符“a”后面的数字,只需指示你的程序将那块内存(对你来说包含'a')视为一个数字。使用演员表。这里:

http://www.cplusplus.com/doc/tutorial/typecasting/

看看是否有帮助!

答案 1 :(得分:2)

想到的一种方法是使用类型特征来定义每种类型的输出类型。您必须手动声明每种类型。这些特征可以定义为一个模板结构,专门用于每种数据类型,它具有与数据类型本身不同的输出类型:

template< T >
struct output_trait {
    typedef const T & output_type;
}

在您的操作员中写下:

std::cout << static_cast< output_trait< T >::output_type >( variable ) << std::endl;

默认情况下不进行强制转换,但对于output_trait专用的类型,它会进行强制转换:

template<>
struct output_trait< unsigned char > {
    typedef unsigned int output_type;
}

答案 2 :(得分:1)

如果我理解你的话......输出就像这样:

std::cout << ( unsigned int )char << '\n';

或更多c ++样式 - 使用static_cast,例如:

int main()
{
    char a = 'a';
    char b = 97;
    std::cout << static_cast< unsigned int >( a ) << '\n';
    std::cout << static_cast< unsigned int >( b ) << '\n';
    return 0;
}

两个std::cout都会打印相同的内容:第一个 - 'a'的ASCII代码:97,第二个 - 只是值97,存储在b中。 ab两者完全相同。

答案 3 :(得分:1)

你可以简单地施展它:

#include<iostream>

int main()
{
 uint8_t blah = 65;
 std::cout << static_cast<int>(blah) << "\n";
 return 0;
}
  

65

答案 4 :(得分:0)

您可以在输出之前强制转换它们:

std::cout << (unsigned int) container[index];