我很好奇std :: setw和std :: setfill的真正返回类型
如我们所见,引用的返回值的数据类型为“未定义”。但是,是否可以声明没有返回类型的函数?
在这种情况下,我必须开发一种为“ cout”或“ cin”提供扩展功能的方法,并且该方法应称为
cout << foo(32, 'A', 0.00f) << "Hello world!";
Run Code Online (Sandbox Code Playgroud)
我应该如何声明该方法?
std::setw未指定et al 的返回类型,因为每种C ++实现可能会决定以不同的方式进行操作,因此没有答案-您必须调查您感兴趣的编译器/版本。
查看与GCC一起使用的libstdc ++,我们看到:
00214 struct _Setw { int _M_n; };
00215
00216 /**
00217 * @brief Manipulator for @c width.
00218 * @param n The new width.
00219 *
00220 * Sent to a stream object, this manipulator calls @c width(n) for
00221 * that object.
00222 */
00223 inline _Setw
00224 setw(int __n)
00225 { return { __n }; }
Run Code Online (Sandbox Code Playgroud)
_Setw是一个捕获width参数的小结构,std::ostream& operator<<(std::ostream&, _Setw)然后...>>...可以处理它以设置流中的宽度:
00227 template<typename _CharT, typename _Traits>
00228 inline basic_istream<_CharT, _Traits>&
00229 operator>>(basic_istream<_CharT, _Traits>& __is, _Setw __f)
00230 {
00231 __is.width(__f._M_n);
00232 return __is;
00233 }
00234
00235 template<typename _CharT, typename _Traits>
00236 inline basic_ostream<_CharT, _Traits>&
00237 operator<<(basic_ostream<_CharT, _Traits>& __os, _Setw __f)
00238 {
00239 __os.width(__f._M_n);
00240 return __os;
00241 }
Run Code Online (Sandbox Code Playgroud)
如我们所见,引用的返回值的数据类型为“未定义”。
它是未指定的,不是未定义的。
但是,是否可以声明没有返回类型的函数?
否-每个函数都必须具有返回类型,即使只有void。
在这种情况下,我必须开发一种为“ cout”或“ cin”提供扩展功能的方法,并且该方法应称为
cout << foo(32, 'A', 0.00f) << "Hello world!";
Run Code Online (Sandbox Code Playgroud)
我应该如何声明该方法?
您可以执行类似的操作并使函数foo返回您为其编写流运算符的对象。然后,这些流函数应该操纵流:您将需要使用iword并xalloc赋予流额外的状态,以跟踪要添加的可能修改的行为-请参见此答案。