首页 > 解决方案 > 如何制作跨度的跨度

问题描述

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);
}

这不编译。我该怎么做这样的事情?

标签: c++c++20std-span

解决方案


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

#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);
}

神螺栓.org

感谢Barry建议上面使用标准范围库的简化概念。


推荐阅读