I have structure:
struct movies_t {
string title;
int year;
}
I would like this structure to have behavior to show it's fields in string.
std:string toString()
{
return "title=" title + "year="+ itostr(year);
}
I can't change struct to class since I should pass it to compiled library which code is unknown. What is the best way to implement this?
There are many ways to implement this. The one I favour is to provide an ADL free-function to_string and an overload of operator<<.
Namespace added for exposition of ADL:
#include <string>
#include <ostream>
#include <sstream>
#include <iostream>
namespace movie
{
struct movies_t {
std::string title;
int year;
};
std::ostream& operator<<(std::ostream& os, movies_t const& arg)
{
os << "title = " << arg.title << ", year = " << arg.year;
}
std::string to_string(movies_t const& arg)
{
std::ostringstream ss;
ss << arg;
return std::move(ss).str(); // enable efficiencies in c++17
}
}
int main()
{
auto m = movie::movies_t { "Star Wars", 1977 };
std::cout << m << '\n';
using std::to_string;
std::cout << to_string(m) << '\n';
}
Since struct
s have public
visibility, you can just inject a member function to the struct directly to do the trick, like this for example:
#include <iostream>
#include <string>
using namespace std;
struct movies_t {
string title;
int year;
string toString()
{
return "title = " + title + ", year = " + to_string(year);
}
};
int main()
{
struct movies_t m{"Odyssey", -800};
cout << m.toString() << endl;
}
Output:
title = Odyssey, year = -800
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With