Delete
Delete

Reputation: 299

Can you implicitly call a method based on an object

I have written a to_string() method for a class I am working on. It is supposed to be used with an operator overload to print a class object. But if I do something like this:

std::ostringstream oss;
oss << Jd(0.5);
BOOST_CHECK_EQUAL( oss.str(), std::string("JD 0.5") );

Instead of calling my to_string() function, it will cast to another operator overload i have for another class. Is there a way I can link my to_string to implicitly print Jd objects even if it isnt directly calling a to_string()? Here's my to_string() method as well:

std::string Jd::to_string() const {

    ostringstream oss;
    oss << "JD " << jd_;
    return oss.str();
} 

Upvotes: 0

Views: 69

Answers (2)

billz
billz

Reputation: 45410

You need to override operator<< for Jd and let it call your to_string() function

std::ostringstream& operator<<(std::ostringstream& os, const Jd& jd)
{
  os << jd.to_string();
  return os;
}

Upvotes: 1

Chad
Chad

Reputation: 19032

You should overload the stream insertion operator (<<) for your Jd class.

class Jd
{
friend std::ostream& operator<<(std::ostream&, const Jd&);
};

std::ostream& operator<<(std::ostream& out, const Jd& obj)
{
   out << "JD " << obj.jd_;
   return out;
}

If you don't want to make the operator<<() function a friend, simply call obj.to_string() instead of directly accessing the obj.jd_ member.

Upvotes: 1

Related Questions