我不确定此代码是否不能编译。流操纵器的模板类型扣除
示例代码我的工作:
#include <iostream>
using std::cout;
using std::endl;
class Foo {
public:
template<typename T>
Foo& operator<<(const T& t) {
cout << t;
return *this;
}
};
int main() {
Foo foo;
foo << "Hello World"; // perfectly fine
foo << endl; // shit hits the fan
return 0;
}
这是错误:
test.cpp:19:12: error: no match for ‘operator<<’ in ‘foo << std::endl’
test.cpp:19:12: note: candidates are:
test.cpp:10:14: note: template<class T> Foo& Foo::operator<<(const T&)
test.cpp:10:14: note: template argument deduction/substitution failed:
test.cpp:19:12: note: couldn't deduce template parameter ‘T’
我很困惑,为什么它不能取代功能型endl
(ostream& (*)(ostream&)
)对于T
,在指定时显然没问题,当您指定cout << endl;
我发现它addi倚重令人费解的是这样可以解决问题[编辑]
Foo& operator<<(ostream& (*f)(ostream&)) {
cout << f;
return *this;
}
如果这个问题不明确,我问为什么它不能推断在首位的模板。
你想达到什么目的?你不是从'std :: basic_ostream'或者实现streambuf派生出来的任何特定原因? –
sehe
2013-02-23 16:41:35
最后一个问题:它首先无法推导出模板,因为**多个重载**是适用的 - 因此函数引用的情况是不明确的。 – sehe 2013-02-23 17:03:04