如何制作跨度跨度

Ayx*_*xan 3 c++ c++20 std-span

C++20std::span是一个非常好的编程接口。但是似乎没有一种简单的方法来获得跨度。这是我想要做的:

#include <iostream>
#include <span>
#include <string>
#include <vector>

void print(std::span<std::span<wchar_t>> matrix) {
  for (auto const& str : matrix) {
    for (auto const ch : str) {
      std::wcout << ch;
    }
    std::wcout << '\n';
  }
}

int main() {
  std::vector<std::wstring> vec = {L"Cool", L"Cool", L"Cool"};
  print(vec);
}
Run Code Online (Sandbox Code Playgroud)

这不编译。我该怎么做?

Pat*_*rts 5

为什么不使用一个概念呢?

#include <iostream>
#include <string>
#include <vector>
#include <ranges>

template <class R, class T>
concept Matrix = 
    std::convertible_to<
        std::ranges::range_reference_t<std::ranges::range_reference_t<R>>,
        T>;

void print(Matrix<wchar_t> auto const& matrix) {
    for (auto const& str : matrix) {
        for (auto const ch : str) {
            std::wcout << ch;
        }
        std::wcout << '\n';
    }
}

int main() {
  std::vector<std::wstring> vec = {L"Cool", L"Cool", L"Cool"};
  print(vec);
}
Run Code Online (Sandbox Code Playgroud)

神箭网

感谢Barry使用标准范围库提出上述简化概念。

  • 这个概念不检查任何东西。或者更确切地说,它要么是“真实的”,要么是格式错误的......这并不是您真正在概念中寻找的东西:https://godbolt.org/z/oE9secK48 (4认同)
  • 并且您可以依赖已经需要“range&lt;R&gt;”的“range_reference_t&lt;R&gt;”,所以简短地说:https://godbolt.org/z/EqWW1n6M1 (2认同)