lundi 28 janvier 2019

C++ Operator<< Overloading to Print Member Variable Values

All -- I have checked existing discussion topics and/or questions on this, and none seems to address this. Hence posting this question. Happy to be referred to an existing link that might already be addressing this exact issue, if I overlooked it.

Below is my snippet of code:

class MyBook{
  public:
    MyBook(): bidPrices(10, 0.0),
              askPrices(10, 0.0),
              bidSizes(10, 0),
              askSizes(10, 0) {}
    std::vector<double> bidPrices;
    std::vector<double> askPrices;
    std::vector<int> bidSizes;
    std::vector<int> askSizes;
};

// Forward declaration
std::unordered_map<std::string, std::unique_ptr<MyBook>> myBookMap;

// Overload << to print.

std::ostream&* operator<<(std::ostream& os, MyBook& mbk)
{
  os << "bid price: " << mbk.bidPrices[0] <<  " "
     << "bid size: " << mbk.bidSizes[0] <<  " "
     << "ask price: " << mbk.askPrices[0] <<  " "
     << "ask size: " << mbk.askSizes[0] << endl;
  return os;
}

Later inside main():

std::unordered_map<std::string, std::unique_ptr<MyBook>>::iterator it = myBookMap.begin();
while (it != myBookMap.end())
{
  std::cout << it->first;
  std::cout << it->second;
}

At compile time, I see "error: no match for 'operator<<'" error.

It possibly couldn't be because of the differing data types between sizes and prices, and even if it is that, I don't see how I can use a template for that when I am passing in the object (mbk) as opposed to a vector (int vector vs. double vector) as the argument to the operator<< overloading function.

Thanks for any insights. Happy to be crucified, although I'm still a newbie.

Best wishes.

Aucun commentaire:

Enregistrer un commentaire