I want to create a function that takes in anything that the <<
operator for std::cout
can handle. I have an example that breaks.
#include <iostream>
template <typename T>
void my_print(const T &t) {
std::cout << t;
}
int main() {
my_print("hello\n"); // works
my_print(4); // works
my_print(std::endl); // compiler error
return 0;
}
It also fails if I change to void my_print(T t)
. The compiler error is
error: no matching function for call to 'my_print(<unresolved overloaded function type>)' note: candidate is note: template<class T> void my_print(const T&)
Why can't the compiler resolve it when it sees that the argument t
is being put into cout
?
Is there any good way to fix this or do I have to manually provide the additional <<
cases, e.g. void my_print(ostream& (*pf)(ostream&));
EDIT: I know endl
is a function. Is the answer then that function types are not accepted as templates? Like I can't have [T = ostream& (*)(ostream&)]
?