Не съм сигурен дали този код няма да се компилира.
Примерният код, с който работя:
#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;
}
В случай, че въпросът не е ясен, питам защо не може да изведе шаблона на първо място.
std::basic_ostream<C,CT>
или да прилагате streambuf? - person sehe   schedule 23.02.2013