Reputation:
I am trying to overload the << operator just for understanding purposes. I was successful but I am having issues with const data types and objects. The compiler gives me the following:
Use of overloaded operator '<<' is ambiguous (with operand types 'std::__1::ostream' (aka 'basic_ostream') and 'const char')
I am using Clion with gcc on MAC and c++ 17. Can someone help me understand what the above error means and how to fix it. Code is below. Thanks!
template <typename T>
std::ostream& operator<<(std::ostream& ost, const T data) {
printf("I am very happy");
return ost;
}
int main() {
const char s = 10;
std::cout << s << std::endl;
}
Upvotes: 0
Views: 93
Reputation: 412
As the above comments mentioned that you cannot overload the primary type for stream out. It had been defined in the standard library. Therefore, in order to print your overlaod, you have to invent some user-type that is not belonging to the primary type, and stream out the user type. This will direct to your overload.
#include <iostream>
template <typename T>
std::ostream& operator<<(std::ostream& ost, const T data) {
printf("I am very happy");
return ost;
}
int main() {
struct mytype{ };
mytype s;
std::cout << s << std::endl;
}
This code will print your string `I am very happy`. Be happy.
Upvotes: 0