如何输出unsigned / signed char或< cstdint>类型作为整数与<<在C ++中 [英] How to output unsigned/signed char or <cstdint> types as integers with << in C++

查看:219
本文介绍了如何输出unsigned / signed char或< cstdint>类型作为整数与<<在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:

我有范本流运算子(例如 operator<<(ostream& std :: vector< T> ;))(输出容器元素可能是一些8位整数类型,例如 unsigned char int_least8_t 等等。

I have template stream operators (e.g. operator << (ostream &, std::vector <T>)) (that output container elements that may possibly be of some 8-bit integer type, (e.g. unsigned char, int_least8_t, et cetera).

问题:

默认是类型输出为 char (ASCII)。
我只使用 char (或
我如何得到这些其他8位类型总是输出 signed int <> / code> / unsigned int (numbers),即使调用者不知道类型吗?

Default is that these types are output as char (ASCII). I only used char (or wchar_t or whatever) for ASCII variables, never unsigned/signed types. How do I get these other 8-bit types to always be output as signed int / unsigned int (numbers) instead, even when the caller doesn't know the type?

首先尝试:

我已经尝试过(使用GCC)定义 operator<<(ostream& unsigned char 值,但是 uint8_t 仍然输出为 char

I have tried (with GCC) for example defining operator << (ostream &, unsigned char) with a cast in it (i.e. stream << static_cast <int> (value). That works for unsigned char values, but then uint8_t still gets output as a char.

相同的底层类型(即 unsigned / signed char 不能在重载中使用,所以我不能定义例如的重载 <& (ostream& amp; int_fast8_t)

The same underlying type (i.e. unsigned/signed char can not be used in overloads, so I can't define an overload of for example operator << (ostream &, int_fast8_t).

推荐答案

以定义每种类型的输出类型。你必须手动为每种类型声明。 traits可以被定义为模板结构,该结构专用于具有与数据类型本身不同的输出类型的每个数据类型:

One way that comes to mind is using type traits to define the output type for each type. You would have to declare that for every type by hand. The traits could be defined as a template struct that is specialized for every data-type that has a different output-type than the data-type itself:

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

在您的运营商中,您写下:

In your operator you write:

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

默认情况下不会转换,但对于 output_trait 是专门的,它将做一个演员:

This will do no cast by default, but for types for which output_trait is specialized it will do a cast:

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

这篇关于如何输出unsigned / signed char或&lt; cstdint&gt;类型作为整数与&lt;&lt;在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆