std::format 的 std::format()able 列表的模板?

问题描述 投票:0回答:1

这样我就可以将任何具有

std::string format()
方法的类的对象传递给
std::format()
:

template<typename T>
requires requires (T v) {
  { v.format() } -> std::convertible_to<std::string>;
}
struct std::formatter<T> : formatter<std::string>
{
  auto format(T t, format_context& ctx) const
  {
    return formatter<std::string>::format(t.format(), ctx);
  }
};

那么,为什么这不适用于此类对象的列表?

template<typename T>
requires requires (T v) {
  { v.format() } -> std::convertible_to<std::string>;
}
struct std::formatter<std::list<T>> : formatter<std::string>
{
  auto format(std::list<T> list, format_context& ctx) const
  {
    std::string result;
    bool first = true;
    for (T& item: list) {
      if (!first)
        result += ", ";

      result += formatter<std::string>::format(item.format(), ctx);

      first = false;
    }

    return result;
  }
};

最终的错误是:

<file>/libutil/include/util/format.h:38:14: error: no match for ‘operator+=’ (operand types are ‘std::string’ {aka ‘std::__cxx11::basic_string<char>’} and ‘std::basic_format_context<std::__format::_Sink_iter<char>, char>::iterator’)
   38 |       result += formatter<std::string>::format(item.format(), ctx);
      |       ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我是否必须以某种方式将

basic_format_context
对象变成
std::string
?怎么办?

c++
1个回答
0
投票

我最终发现我的

.format()
formatter<>::format()
调用方式错误:

template<typename T>
requires requires (T v) {
  { v.format() } -> std::convertible_to<std::string>;
}
struct std::formatter<std::list<T>> : formatter<std::string>
{
  auto format(std::list<T> list, format_context& ctx) const
  {
    std::string result;
    bool first = true;
    for (T& item: list) {
      if (!first)
        result += ", ";

      result += item.format();

      first = false;
    }

    return formatter<std::string>::format(result, ctx);
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.