0

Not able to understand why getting error

error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream’} and ‘MyStruct’) cout << st;

in the below code

#include <iostream>
using namespace std;

struct MyStruct
{
    int a;
    string b;
    double c;
    
    MyStruct(int a, string b, double c):a(a),b(b),c(c){}
    
    ostream& operator<<(ostream& os)
    {
        os << "a " << a << " b" << b << " c" << c;
        return os;
    }
};

template <typename T, typename ... Args>
T create(Args&& ... Arg)
{
    return T(Arg...);
}

int main() {
    // your code goes here
    MyStruct st = create<MyStruct>(5, "My Struct", 2.5);
    cout << st;
    return 0;
}
1
  • 1
    You define an << where you can do st << cout. Commented May 9, 2021 at 2:32

1 Answer 1

4

The correct signature for the operator is:

    friend ostream& operator<<(ostream& os, const MyStruct& dt);

Right now your output stream operator is only overloaded in a way that allows st << cout.

Sign up to request clarification or add additional context in comments.

2 Comments

It worked thanks. Can you please point out what is the difference between these two.
@user1685827 It's already pointed out. You have a signature which is compatible with the parameters to st << cout, when you need one that declares a free function that takes the arguments in the order os, dt for cout << st.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.