带参数的流操纵器如何工作

带参数的流操纵器如何工作

本文介绍了带参数的流操纵器如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

在Stroustrup的C ++书籍中,有一个使用参数的自定义操纵器的示例(请参见随附的代码).我对结构的创建方式感到困惑.特别是,对于"smanip"的构造函数,似乎有两个int参数,一个用于函数指针"ff",一个用于"ii".我不明白如何通过使用int参数来创建结构:

In Stroustrup's C++ book, there is an example of a custom manipulator taking an argument (pls see the attached code). I am confused about how the struct is created. In particular, it looks like there are two int arguments for the constructor of "smanip", one for the function pointer "ff", one for "ii". I don't understand how the int argument is passed to create the structure by using:

cout << setprecision(4) << angle;

此外,这些函数的调用顺序是什么,以及如何确定类型参数Ch和Tr?非常感谢.

In addition, what is the order these functions get called, and how the the type arguments Ch and Tr are determined? Thanks a lot.

// manipulator taking arguments
struct smanip{
    iso_base& (*f) (ios_base&, int);
    int i;
    smanip(ios_base& (*ff)(ios_base&, int), int ii) : f(ff), i(ii){}
};

template<cladd Ch, class Tr>
ostream<Ch, Tr>& operator<<(ostream<Ch, Tr>& os, smanip& m){
    return m.f(os, m.i);
}

ios_base& set_precision(ios_base& s, int n){
    return s.setprecision(n); // call the member function
}

inline smanip setprecision(int n){
    return smanip(set_precision,n);
}

// usage:
cout << setprecision(4) << angle;

推荐答案

setprecision(4)

通话

inline smanip setprecision(int n){
    return smanip(set_precision,n);
}

从指向set_precision函数的指针和n创建一个smanip.

Which creates an smanip from a pointer to the set_precision function, and n.

struct smanip{
    ios_base& (*f) (ios_base&, int);
    int i;
    smanip(ios_base& (*ff)(ios_base&, int), int ii) : f(ff), i(ii){}
};

smanip是保存指向函数的指针和整数的结构.该函数通过引用获取ios_baseint,并通过引用返回ios_base.

smanip is a struct that holds a pointer to a function, and an integer. That function takes an ios_base by reference and an int, and returns the ios_base by reference.

此时,该行实际上是这样的:

At this point the line is effectively like this:

smanip m(&setprecision, 4);
cout << m << (otherstuff);

与该模板匹配的

template<class Ch, class Tr>
ostream<Ch, Tr>& operator<<(ostream<Ch, Tr>& os, smanip& m){
    return m.f(os, m.i);
}

然后编译器可以从左侧的流中推断出ChTr.在这种情况下,为std::cout.该代码执行m.f(os, m.i).这将调用smanip保留的函数指针,并向其传递流和smanip保留的整数.

And the compiler can deduce Ch, and Tr from the stream on the left side. In this case, std::cout. The code executes m.f(os, m.i). This calls the function pointer held by the smanip, passing it the stream and the integer held by smanip.

ios_base& set_precision(ios_base& s, int n){
    return s.setprecision(n); // call the member function
}

这将调用cout.setprecision(n).

因此该行翻译为:

std::cout.setprecision(4) << angle;

这篇关于带参数的流操纵器如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 17:56