Dan Andreasson
Dan Andreasson

Reputation: 16212

How to send two tuples as arguments in C++

Hello i am new to C++ and im trying to make a program that takes two complex numbers, sumarizes them and return the sum.

What i am planning to do is sending two tuples into a function and returning one tuple.

typedef tuple<float, float> complex_tuple;
  complex_tuple a_tuple(a, b);
  complex_tuple b_tuple(c, d);


    cout << sum(a_tuple, b_tuple);

and this is my function:

tuple<float,float> sum(tuple<float, float>a, tuple<float, float>b){
  float a_real= get<0>(a);
  float a_imag= get<1>(a);
  float b_real= get<0>(b);
  float b_imag= get<1>(b);
  return tuple<float, float>(a_real+b_real, a_imag+b_imag);
}

the error i get is:

0.cc:28:31: Error: no match for "operator<<" in "std::cout << sum(std::tuple<float, float>, std::tuple<float, float>)(b_tuple)"

What am i doing wrong?

Upvotes: 3

Views: 323

Answers (3)

Jon
Jon

Reputation: 437386

You are trying to say that you want to print the sum to cout, but cout doesn't know how to handle values of type complex_tuple.

Provide an overload of operator<<(ostream&, const complex_tuple&) to allow the code to compile:

ostream& operator<<(ostream& os, const complex_tuple& tuple) {
    os << get<0>(tuple) << "+" << get<1>(tuple) << "i";
    return os;
}

Further information.

Upvotes: 5

john
john

Reputation: 8027

The error says operator<<. There's nothing wrong with the code you've posted except you haven't written this function yet.

ostream& operator<<(ostream& out, const complex_tuple& x);

Write that function and the error will go away.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258618

Your assumption that an overload for std::cout and operator<<(std::tuple) exists is wrong. The error message is pretty clear on that.

You'll need to print the elements of the tuple separately.

Upvotes: 3

Related Questions