0

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;
}
  • Does this answer your question? [overloading friend operator<< for template class](https://stackoverflow.com/questions/4660123/overloading-friend-operator-for-template-class) – Krishna Kanth Yenumula Dec 22 '20 at 14:51
  • `cout << s` with `char s` is already defined by the standard library. Roughly put, your template defines `cout << s` for all types `T`, including `char`. The compiler can not understand which implementation to choose since two are in scope. You should not redefine `<<` for standard types. – chi Dec 22 '20 at 15:05

1 Answers1

0

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.

ytlu
  • 412
  • 4
  • 9