我正在创建一个自定义的 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/