[英]Custom stream manipulator for streaming integers in any base
例如,我可以使用十六进制的std::ostream
对象输出整数
std::cout << std::hex << 0xabc; //prints `abc`, not the base-10 representation
所有基地都有通用的操纵器吗? 就像是
std::cout << std::base(4) << 20; //I want this to output 110
如果有,那我就没有其他问题了。 如果没有,那我可以写一个吗? 它不会要求我访问std::ostream
私有实现细节吗?
请注意,我知道我可以编写一个函数,它接受一个数字并将其转换为一个字符串,该字符串是任何基数中该数字的表示。 或者我可以使用已经存在的。 我问的是自定义流操纵器 - 它们可能吗?
提前致谢
您可以执行以下操作。 我已经评论了代码来解释每个部分正在做什么,但基本上它是这样的:
这是代码......
编辑:请注意,我不确定我在这里正确处理了std::ios_base::internal
标志 - 因为我实际上并不知道它的用途。
编辑2:我发现了std::ios_base::internal
的用途,并更新了代码来处理它。
编辑3:添加了对std::locacle::global
的调用,以显示默认情况下如何使所有标准流类支持新的流操纵器,而不是必须imbue
它们。
#include <algorithm>
#include <cassert>
#include <climits>
#include <iomanip>
#include <iostream>
#include <locale>
namespace StreamManip {
// Define a base manipulator type, its what the built in stream manipulators
// do when they take parameters, only they return an opaque type.
struct BaseManip
{
int mBase;
BaseManip(int base) : mBase(base)
{
assert(base >= 2);
assert(base <= 36);
}
static int getIWord()
{
// call xalloc once to get an index at which we can store data for this
// manipulator.
static int iw = std::ios_base::xalloc();
return iw;
}
void apply(std::ostream& os) const
{
// store the base value in the manipulator.
os.iword(getIWord()) = mBase;
}
};
// We need this so we can apply our custom stream manipulator to the stream.
std::ostream& operator<<(std::ostream& os, const BaseManip& bm)
{
bm.apply(os);
return os;
}
// convience function, so we can do std::cout << base(16) << 100;
BaseManip base(int b)
{
return BaseManip(b);
}
// A custom number output facet. These are used by the std::locale code in
// streams. The num_put facet handles the output of numberic values as characters
// in the stream. Here we create one that knows about our custom manipulator.
struct BaseNumPut : std::num_put<char>
{
// These absVal functions are needed as std::abs doesnt support
// unsigned types, but the templated doPutHelper works on signed and
// unsigned types.
unsigned long int absVal(unsigned long int a) const
{
return a;
}
unsigned long long int absVal(unsigned long long int a) const
{
return a;
}
template <class NumType>
NumType absVal(NumType a) const
{
return std::abs(a);
}
template <class NumType>
iter_type doPutHelper(iter_type out, std::ios_base& str, char_type fill, NumType val) const
{
// Read the value stored in our xalloc location.
const int base = str.iword(BaseManip::getIWord());
// we only want this manipulator to affect the next numeric value, so
// reset its value.
str.iword(BaseManip::getIWord()) = 0;
// normal number output, use the built in putter.
if (base == 0 || base == 10)
{
return std::num_put<char>::do_put(out, str, fill, val);
}
// We want to conver the base, so do it and output.
// Base conversion code lifted from Nawaz's answer
int digits[CHAR_BIT * sizeof(NumType)];
int i = 0;
NumType tempVal = absVal(val);
while (tempVal != 0)
{
digits[i++] = tempVal % base;
tempVal /= base;
}
// Get the format flags.
const std::ios_base::fmtflags flags = str.flags();
// Add the padding if needs by (i.e. they have used std::setw).
// Only applies if we are right aligned, or none specified.
if (flags & std::ios_base::right ||
!(flags & std::ios_base::internal || flags & std::ios_base::left))
{
std::fill_n(out, str.width() - i, fill);
}
if (val < 0)
{
*out++ = '-';
}
// Handle the internal adjustment flag.
if (flags & std::ios_base::internal)
{
std::fill_n(out, str.width() - i, fill);
}
char digitCharLc[] = "0123456789abcdefghijklmnopqrstuvwxyz";
char digitCharUc[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const char *digitChar = (str.flags() & std::ios_base::uppercase)
? digitCharUc
: digitCharLc;
while (i)
{
// out is an iterator that accepts characters
*out++ = digitChar[digits[--i]];
}
// Add the padding if needs by (i.e. they have used std::setw).
// Only applies if we are left aligned.
if (str.flags() & std::ios_base::left)
{
std::fill_n(out, str.width() - i, fill);
}
// clear the width
str.width(0);
return out;
}
// Overrides for the virtual do_put member functions.
iter_type do_put(iter_type out, std::ios_base& str, char_type fill, long val) const
{
return doPutHelper(out, str, fill, val);
}
iter_type do_put(iter_type out, std::ios_base& str, char_type fill, unsigned long val) const
{
return doPutHelper(out, str, fill, val);
}
};
} // namespace StreamManip
int main()
{
// Create a local the uses our custom num_put
std::locale myLocale(std::locale(), new StreamManip::BaseNumPut());
// Set our locacle to the global one used by default in all streams created
// from here on in. Any streams created in this app will now support the
// StreamManip::base modifier.
std::locale::global(myLocale);
// imbue std::cout, so it uses are custom local.
std::cout.imbue(myLocale);
std::cerr.imbue(myLocale);
// Output some stuff.
std::cout << std::setw(50) << StreamManip::base(2) << std::internal << -255 << std::endl;
std::cout << StreamManip::base(4) << 255 << std::endl;
std::cout << StreamManip::base(8) << 255 << std::endl;
std::cout << StreamManip::base(10) << 255 << std::endl;
std::cout << std::uppercase << StreamManip::base(16) << 255 << std::endl;
return 0;
}
定制操纵器确实是可能的。 例如,请参阅此问题 。 我对通用基地的任何特定基础都不熟悉。
你真的有两个不同的问题。 我认为你问的那个是完全可以解决的。 不幸的是,另一个则不那么重要了。
分配和使用流中的一些空间来保持某些流状态是一个预见的问题。 Streams有几个成员( xalloc
, iword
, pword
),可以让你在流中的数组中分配一个点,并在那里读/写数据。 因此,流操纵器本身是完全可能的。 您基本上使用xalloc
在流的数组中分配一个点以保存当前基数,以便插入运算符在转换数字时使用。
为此,我没有看到一个解决方案的问题是相当简单:标准库中已经提供了一个operator<<
插入一个int
成流,这显然不知道你的假设数据,以保持转换的基础。 你不能重载它,因为它需要与现有签名完全相同的签名,所以你的重载将是模糊的。
但是, int
, short
等的重载是重载的成员函数。 我想如果你想要足够严重,你可以使用模板来重载operator<<
。 如果我没记错的话,那就像图书馆提供的那样,甚至与非模板功能完全匹配也是首选。 你仍然违反规则,但如果你把这样的模板放在命名空间std中,那么它至少有一些机会可以运行。
我试图编写代码,并且它有一些限制。 它本身不是流操纵者,因为根本不可能,正如其他人所指出的那样(特别是@Jerry)。
这是我的代码:
struct base
{
mutable std::ostream *_out;
int _value;
base(int value=10) : _value(value) {}
template<typename T>
const base& operator << (const T & data) const
{
*_out << data;
return *this;
}
const base& operator << (const int & data) const
{
switch(_value)
{
case 2:
case 4:
case 8: return print(data);
case 16: *_out << std::hex << data; break;
default: *_out << data;
}
return *this;
}
const base & print(int data) const
{
int digits[CHAR_BIT * sizeof(int)], i = 0;
while(data)
{
digits[i++] = data % _value;
data /= _value;
}
while(i) *_out << digits[--i] ;
return *this;
}
friend const base& operator <<(std::ostream& out, const base& b)
{
b._out = &out;
return b;
}
};
这是测试代码:
int main() {
std::cout << base(2) << 255 <<", " << 54 << ", " << 20<< "\n";
std::cout << base(4) << 255 <<", " << 54 << ", " << 20<< "\n";
std::cout << base(8) << 255 <<", " << 54 << ", " << 20<< "\n";
std::cout << base(16) << 255 <<", " << 54 << ", " << 20<< "\n";
}
输出:
11111111, 110110, 10100
3333, 312, 110
377, 66, 24
ff, 36, 14
在线演示: http : //www.ideone.com/BWhW5
限制:
基地不能改变两次。 所以这将是一个错误:
std::cout << base(4) << 879 << base(8) << 9878 ; //error
使用base
后,不能使用其他操纵器:
std::cout << base(4) << 879 << std::hex << 9878 ; //error std::cout << std::hex << 879 << base(8) << 9878 ; //ok
使用base
后不能使用std::endl
:
std::cout << base(4) << 879 << std::endl ; //error //that is why I used "\\n" in the test code.
我不认为语法可以用于任意流(使用操纵器,@ gigantt链接一个显示一些替代非操纵器解决方案的答案)。 标准操纵器仅设置在流内实现的选项。
OTOH,你当然可以使这个语法工作:
std::cout << base(4, 20);
其中base
是一个提供流插入操作符的对象(不需要返回临时string
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.