c++ - 如何在自定义 std::ostream 类中使用 std::endl

标签 c++ templates std

我正在创建一个自定义的 ostream 类,它在以下代码片段中进行了简要介绍。我希望能够使用 std::endl 但编译器不允许。我不明白为什么。

#include <iostream> 

struct Bar
{
};

template <typename T>
struct Foo
{
};

template <typename T, typename U>
Foo<T>& operator<<(Foo<T>& _foo, U&&)
{
  return _foo;
}

int main()
{
  Foo<Bar> f;
  f << "aa" << std::endl;
}

gcc 4.7.1 给我的错误是:

main.cpp:21:21: error: no match for ‘operator<<’ in ‘operator<< ((* & f), (*"aa")) << std::endl’ main.cpp:21:21: note: candidates are: main.cpp:13:9: note: template Foo& operator<<(Foo&, U&&) main.cpp:13:9: note: template argument deduction/substitution failed: main.cpp:21:21: note:
couldn't deduce template parameter ‘U’

为什么不能推导出参数U?这不应该是 typeof(std::endl) 吗?

最佳答案

因为 std::endl

namespace std {
template <class charT, class traits>
basic_ostream<charT,traits>& endl(basic_ostream<charT,traits>& os);
}

你的类不是从 basic_ostream 派生的,所以它不能工作。

basic_ostream

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

for 与像 std::endl 这样的操纵器一起工作。

关于c++ - 如何在自定义 std::ostream 类中使用 std::endl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12333858/

相关文章:

c++ - C++中通过引用返回值

c++ - 将模板函数的类型传递给其中使用的模板类?

c++ - 嵌套模板函数采用 2 个具有相同内部类型的容器

c++ - set_difference 和 set_intersection 同时进行

c++ - C++ 中对 union { } 的需求是什么?

c++ - 我可以在 C++ 中使用 ReadDirectoryChangesW() 来观察多个目录的变化吗?

visual-studio - T4 模板与 TT 模板与 visual studio 中的包含

c++ - std 函数 std::_Rb_tree_rebalance_for_erase () 中的段错误

c++ - 关于将 std::less 和 std::greater 与 std::sort 一起使用的困惑

c++ - Freetype 和 OpenGL 的问题