以优雅的方式串起来的结构

新手上路,请多包涵

我有结构:

 struct movies_t {
  string title;
  int year;
}

我希望这个结构具有在字符串中显示它的字段的行为。

 std:string toString()
{
return "title=" title + "year="+ itostr(year);
}

我不能将结构更改为类,因为我应该将它传递给代码未知的编译库。实现这一点的最佳方法是什么?

原文由 vico 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 552
1 个回答

有很多方法可以实现这一点。我喜欢的是提供一个 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';
}

原文由 Richard Hodges 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏