结构优雅

vic*_*ico 6 c++ struct

我有结构:

struct movies_t {
  string title;
  int year;
} 
Run Code Online (Sandbox Code Playgroud)

我希望这种结构具有行为以字符串形式显示其字段。

std:string toString()
{
return "title=" title + "year="+ itostr(year);
}
Run Code Online (Sandbox Code Playgroud)

我无法将struct更改为class,因为我应该将其传递给代码未知的编译库。实现此目的的最佳方法是什么?

gsa*_*ras 6

由于structs 具有public可见性,您可以直接向结构体注入成员函数来实现这一点,例如:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

标题 = 奥德赛,年份 = -800


Ric*_*ges 6

有很多方法可以实现这一点。我喜欢的是提供 ADL 自由函数 to_string 和 operator<< 的重载。

添加命名空间以说明 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';
}
Run Code Online (Sandbox Code Playgroud)