Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structure to string in elegant way

Tags:

c++

struct

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?

like image 679
vico Avatar asked Jan 19 '18 08:01

vico


2 Answers

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';
}
like image 95
Richard Hodges Avatar answered Oct 15 '22 12:10

Richard Hodges


Since structs 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

like image 39
gsamaras Avatar answered Oct 15 '22 10:10

gsamaras