【问题标题】:Parametrized custom stream manipulators - why overload "operator<<"?参数化自定义流操纵器 - 为什么重载“operator<<”?
【发布时间】:2021-11-26 05:38:09
【问题描述】:

我正在尝试为一组数据实现参数化流操纵器。我按照推荐的简单方法来做:

class print_my_data
{
private:
    . . .

public:
    print_my_data(. . .) { . . . }

    ostream& operator()(std::ostream& out)
    {
        return out << . . . << endl;
    }
};

ostream& operator<<(ostream& out, print_my_data md) // <=== MY QUESTION BELOW IS ABOUT THIS
{
    return md(out);
}

用法:

clog << print_my_data(. . .) << endl;

这很好用;但我真的不明白为什么它不起作用,除非我定义operator&lt;&lt;!为什么它不调用与endl 相同的重载函数? (即作为可以通过operator()应用于流的对象)

【问题讨论】:

    标签: c++ iostream manipulators


    【解决方案1】:

    您要查找的overload 仅为函数指针定义。

    basic_ostream& operator<<(
       std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );
    

    你的print_my_data 类是一个可调用对象(一个函子,在C++ 术语中)。但它不是函数指针。另一方面,endl 是一个函数,因此有一个函数指针(事实上,它是 C++ 标准库中为数不多的确实有地址的函数之一)

    可以提出一个不合理的论点,即重载应该看起来像

    basic_ostream& operator<<(
       std::function<std::basic_ostream<CharT,Traits>&(std::basic_ostream<CharT,Traits>&)> func);
    

    但是,在编写 I/O 操作运算符时,std::function 并不存在。就此而言,概念也不是。并使用SFINAE声明

    template <typename F>
    basic_ostream& operator<<(
       F func);
    

    会打开一整个潘多拉魔盒,里面满是标准委员会不想处理的杂乱细节。

    【讨论】:

    • 反正函数指针和print_my_data都不是std::function,所以也不会选择重载。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2010-11-11
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多