【问题标题】:Why do C++ stream manipulators not have a call operator?为什么 C++ 流操作符没有调用操作符?
【发布时间】:2014-03-08 11:24:00
【问题描述】:

我想知道:如果例如std::endl 是一个常规函数,那么为什么它缺少调用运算符(operator())?

我知道它被设计为与插入 (<<) 和提取 (>>) 运算符一起使用。我试着这样称呼它:

std::endl.();

但这当然没有用。

【问题讨论】:

  • 函数没有“呼叫操作员”。只有类可以。可以调用函数,因为这是核心语言的一部分。 printf 也没有呼叫接线员。
  • 致电std::endl() 时您期望什么?
  • 完全不是答案,但如果您正在尝试拼写函数调用运算符,并且如果它存在,它将被拼写为:std::endl.operator()(args);

标签: c++ c++11 manipulators


【解决方案1】:

std::endl 只是一个可以调用的普通函数(或者更确切地说,函数模板)。您只需使用正确的参数调用它:

std::endl(std::cout);    // OK, equivalent to "std::cout << std::endl;"

这是因为ostream 重载了函数指针的移位运算符,其方式等同于以下内容:

ostream & operator<<(ostream & os, ostream & (*f)(ostream &))
{
    return f(os);
}

(它实际上是basic_ostream 处理任何类型的字符特征和分配器的模板。)

【讨论】:

    猜你喜欢
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 2011-08-28
    • 1970-01-01
    相关资源
    最近更新 更多