我正在创建一个自定义 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;
}
Run Code Online (Sandbox Code Playgroud)
gcc 4.7.1 给我的错误是:
main.cpp:21:21: 错误: 'operator<< ((* & f), (*"aa")) << std::endl' main.cpp:21 中的 'operator<<' 不匹配: 21:注意:候选是:main.cpp:13:9:注意:模板Foo& operator<<(Foo&, U&&) main.cpp:13:9:注意:模板参数推导/替换失败:main.cpp:21: 21:注意:
无法推导出模板参数“U”
为什么不能推导出参数U?这不应该typeof(std::endl)吗?
由于std::endl是
namespace std {
template <class charT, class traits>
basic_ostream<charT,traits>& endl(basic_ostream<charT,traits>& os);
}
Run Code Online (Sandbox Code Playgroud)
你的类不是从 派生的basic_ostream,所以它不能工作。
并且basic_ostream有
basic_ostream<charT,traits>& operator<<
(basic_ostream<charT,traits>& (*pf)(basic_ostream<charT,traits>&))
Run Code Online (Sandbox Code Playgroud)
用于像std::endl.