gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:35:45 25 4
gpt4 key购买 nike

在下面的代码中:

#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代码说:
Type deduction error screenshot
编译器将生成以下内容:
$ 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>专门化)的对象,因此auto可以推断出其类型。std::endl根本不是对象,它是模板函数(特别是,将模板化的std::basic_ostream对象作为参数的流操纵器):

template< class CharT, class Traits >
std::basic_ostream<CharT, Traits>& endl( std::basic_ostream<CharT, Traits>& os );
作为模板, std::endl可以处理不同字符类型( charwchar_t等)的输出流,即 std::coutstd::wcout等。
但是,您没有为模板参数提供任何值来告诉编译器您要使用哪种 std::endl特化,因此 auto无法为其推断出具体类型,因此会产生错误。
您将不得不执行以下操作:
auto& end = std::endl<char, std::char_traits<char>>;
Live Demo

关于c++ - 为什么std::endl的类型推导失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63329986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com