gpt4 book ai didi

c++ - 为什么 std::num_put 通过非 const 引用获取 ios_base 参数?

转载 作者:行者123 更新时间:2023-11-30 04:10:59 25 4
gpt4 key购买 nike

我正在试验 iostreams/locale numeric facet,我遇到了一些非常奇怪的事情:

使用 std::num_put facet 的“典型示例”直接格式化一个数字是这样的:

std::string f(double value) {
using namespace std;
stringstream ss;
num_put<char> const& npf = use_facet<num_put<char> >(ss.getloc());
npf.put(/*out=*/ss, /*format=*/ss, /*fill=*/' ', value);
return ss.str();
}

第一个参数put是写入输出的地方。

我们也可以有这样的代码并且它有效:

std::string g(double value) {
using namespace std;
stringstream ss;
typedef char* CharBufOutIt;
num_put<char, CharBufOutIt> const& npf = use_facet<num_put<char, CharBufOutIt> >(ss.getloc());
char big_enough_buf[100];
npf.put(/*out=*/big_enough_buf, /*format=*/ss, /*fill=*/' ', value);
return big_enough_buf;
}

put()第二个参数 是一个流对象,它确定要应用的特定格式。第二个参数根本未修改。 (不是在我的实现中,也不是根据 the docs describe 这个参数的用途。)

但是,put 的签名是这样的:

iter_type put( iter_type out, std::ios_base& str, char_type fill, long double v ) const;

也就是说,它通过非 const 引用获取 ios_base 对象,即使看起来它实际上应该通过const 引用获取它。

我错过了什么吗?这只是 C++ iostreams 规范中的一个(历史?)特性吗? C++ 标准委员会是否讨论过这个问题?

最佳答案

来自Standard (22.4.2.2.2) put 的实现是这样的:

Stage 3:

If str.width() is nonzero and the number of charT’s in the sequence after stage 2 is less than str.width(), then enough fill characters are added to the sequence at the position indicated for padding to bring the length of the sequence to str.width(). str.width(0) is called.`

此外,str.width(0) 调用未声明 constwidth(参见 this link):

streamsize ios_base::width (streamsize wide);

关于c++ - 为什么 std::num_put 通过非 const 引用获取 ios_base 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20380274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com