如何实现iomanip函数? [英] How are iomanip Functions Implemented?

查看:205
本文介绍了如何实现iomanip函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些标准的 iomanip 函数接受一个参数。

Some of the standard iomanip functions take take a parameter.

我想知道如何是完成了,例如,我可以做一些类似的功能吗?这真的是我需要这个答案的解决方案,但我不知道该怎么做。

I'd like to know how this is accomplished, for instance, can I do something similar with a function? That's really the solution that I needed for this answer, but I couldn't figure out how to do this.

当我查找 setw 函数的定义时,例如在 http://en.cppreference.com 它将返回类型列为未指定,并且它也只列出一个参数,而不是也采取一个流& 参数。

When I looked up the definition for setw function for example in http://en.cppreference.com it lists the return type as "unspecified", and it also only lists one argument, rather than also taking a stream& parameter. How does this work?

推荐答案

这里是一个用户定义的操纵器的简单示例,它使用一个类定义了一个参数:

Here is a simple example of a user-defined manipulator that takes one parameter defined using a class:

#include <iostream>

class putX // injects some `X`s into the stream
{
    std::size_t _n;
public:
    explicit putX(std::size_t n): _n(n) {}
    std::size_t getn() const {return _n;}
    friend std::ostream& operator<<(std::ostream& os, const putX& obj)
    {
        std::size_t n = obj.getn();
        for (std::size_t i = 0; i < n; ++i)
            os << 'X';
        return os;
    }
};

int main()
{
    std::cout << putX(10) << " test " << putX(10);
}

不带参数的操纵器可以简单地实现为

Manipulators that take no parameters can simply be implemented as

std::ostream& custom_manip(std::ostream& os) { // do something with os and return os;}

这是因为 basic_ostream :: operator<< 有一个重载,它接受一个指针函数 std :: ostream& (* fp)(std :: ostream&)为其右手侧(例如,操纵器)

That's because basic_ostream::operator<< has an overload that takes a pointer-to-function std::ostream& (*fp)(std::ostream&) as its right hand side (e.g., a manipulator)

PS: C ++标准库描述了操纵器/自定义操纵器是如何工作的很详细,见第。 15.6.3 用户定义的操纵符

PS: The C++ Standard Library by N. Josuttis describes how manipulators/custom manipulators work in great detail, see Sec. 15.6.3 User-Defined Manipulators

这篇关于如何实现iomanip函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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