gpt4 book ai didi

c++ - 为什么 std::endl 会生成这个神秘的错误消息?

转载 作者:可可西里 更新时间:2023-11-01 17:21:33 26 4
gpt4 key购买 nike

如果我尝试编译以下代码,我会得到以下编译器错误(请参阅代码。)如果删除了 std::endl,它编译时不会出错。

#include <iostream>
#include <sstream>
#include <utility>

namespace detail
{
template <class T>
void print(std::ostream& stream, const T& item)
{
stream << item;
}

template <class Head, class... Tail>
void print(std::ostream& stream, const Head& head, Tail&&... tail)
{
detail::print(stream, head);
detail::print(stream, std::forward<Tail>(tail)...);
}
}

template <class... Args>
void print(std::ostream& stream, Args&&... args)
//note: candidate function not viable: requires 3 arguments, but 4 were provided
{
std::stringstream ss;
detail::print(ss, std::forward<Args>(args)...);
stream << ss.rdbuf();
}

int main()
{
print(std::cout, "The answer is ", 42, std::endl);
//error: no matching function for call to 'print'
}

最佳答案

std::endl 是一个函数模板。使用时,其模板参数必须由编译器显式指定或推导。

std::ostream 有重载:

basic_ostream<charT,traits>& operator<<(
basic_ostream<charT,traits>& (*pf) (basic_ostream<charT,traits>&) );

当我们使用

std::cout << std::endl;

编译器推断用于std::endl 的类型。由于在调用 print 时无法回退到自动类型推导,因此您必须明确说明要使用哪个版本的 std::endl .

以下应该有效:

print(std::cout, "The answer is ", 42, std::endl<char, std::char_traits<char>>);

更新

我使用以下精简代码来跟踪问题:

#include <iostream>

namespace detail
{
template <class T>
void print(std::ostream& stream, const T& item)
{
stream << item;
}
}

int main()
{
// detail::print(std::cout, std::endl);
detail::print(std::cout, std::endl<char, std::char_traits<char>>);
}

关于c++ - 为什么 std::endl 会生成这个神秘的错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24377892/

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