简体   繁体   English

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

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

In the following code:在以下代码中:

#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;
}

The type deduction for std::cout takes place properly, but why doesn't it works for std::endl ? std::cout的类型推导正确进行,但为什么它不适用于std::endl

Note: Removing the reference to operator (ampersand) doesn't works either.注意:删除对运算符(与号)的引用也不起作用。


The VS Code says: VS 代码说:

类型扣除错误截图

And the compiler generates the following:编译器生成以下内容:

$ 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 is an object of a concrete type std::ostream (aka the std::basic_ostream<char> specialization), so auto can deduce its type. 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): 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 );

Being a template allows std::endl to work with output streams of different character types ( char , wchar_t , etc), ie std::cout vs std::wcout , etc.作为模板允许std::endl使用不同字符类型( charwchar_t等)的 output 流,即std::coutstd::wcout等。

But, you are not providing any values for the template parameters to tell the compiler which specialization of std::endl you want to use, so auto can't deduce a concrete type for it, hence the error.但是,您没有为模板参数提供任何值来告诉编译器您要使用std::endl的哪个专业化,因此auto无法为其推断出具体类型,因此会出现错误。

You would have to do something like this instead:您将不得不这样做:

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

Live Demo现场演示

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

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