このコードがコンパイルされないかどうかはわかりません。
私が使用しているサンプルコード:
#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;
これで問題が解決するのはさらに不可解だと思います[編集済み]
Foo& operator<<(ostream& (*f)(ostream&)) {
cout << f;
return *this;
}
質問が明確でない場合は、そもそもなぜテンプレートを推測できなかったのかを尋ねています。