【问题标题】:Why can't std::endl be passed as a function argument?为什么 std::endl 不能作为函数参数传递?
【发布时间】:2021-07-18 07:17:21
【问题描述】:
#include <iostream>

void f(auto x)
{
    std::cout << x;
}

int main()
{
    f(std::hex);  // okay

    f(std::endl); // error
                  // candidate template ignored: 
                  // couldn't infer template argument 'x:auto'
}

为什么不能将std::endl 作为函数参数传递?

【问题讨论】:

    标签: c++ overloading iostream template-argument-deduction


    【解决方案1】:

    因为std::endl 是函数模板,而std::hex 不是,所以它是单个非重载函数。

    将引用整个重载集的函数作为参数传递是通过解析为单个具体类型来完成的。

    这里发生的情况是调用者希望通过尝试使f 函数解析它来解析类型,但f 函数希望调用者解析为特定类型,因此它知道要推断什么。 “坚不可摧的盾遇上剑被剑击破了所有盾牌”的情况。

    【讨论】:

      猜你喜欢
      • 2021-10-10
      • 2011-10-27
      • 2012-04-18
      • 2017-08-31
      • 1970-01-01
      • 2013-11-19
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      相关资源
      最近更新 更多