繁体   English   中英

为什么 std::endl 的类型推导失败?

[英]Why does the type deduction for std::endl fails?

在以下代码中:

#include <iostream>

auto& print = std::cout; // Type deduction for std::cout works
auto& end = std::endl;   // But the std::endl is exception here

int main(void) {
  print << "Hello" << end;

  return 0;
}

std::cout的类型推导正确进行,但为什么它不适用于std::endl

注意:删除对运算符(与号)的引用也不起作用。


VS 代码说:

类型扣除错误截图

编译器生成以下内容:

$ g++ -Wall -O3 -std=c++14 -o main main.cpp; ./main

main.cpp:4:18: error: unable to deduce 'auto&' from 'std::endl'
    4 | auto& end = std::endl;    // But the std::endl is exception here
      |                  ^~~~
main.cpp:4:18: note:   couldn't deduce template parameter 'auto'

std::cout是具体类型std::ostream (又名std::basic_ostream<char>特化)的 object ,因此auto可以推断其类型。

std::endl is not an object at all, it is a template function (specifically, a stream manipulator taking a templated std::basic_ostream object as a parameter):

template< class CharT, class Traits >
std::basic_ostream<CharT, Traits>& endl( std::basic_ostream<CharT, Traits>& os );

作为模板允许std::endl使用不同字符类型( charwchar_t等)的 output 流,即std::coutstd::wcout等。

但是,您没有为模板参数提供任何值来告诉编译器您要使用std::endl的哪个专业化,因此auto无法为其推断出具体类型,因此会出现错误。

您将不得不这样做:

auto& end = std::endl<char, std::char_traits<char>>;

现场演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM