如何制作跨度跨度
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);
}
这不编译。我该怎么做?
回答
为什么不使用一个概念呢?
#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);
}
神箭网
感谢Barry使用标准范围库提出上述简化概念。
- That concept doesn't check anything. Or rather, it's either `true` or ill-formed... which isn't really what you're looking for in a concept: https://godbolt.org/z/oE9secK48
- And you can rely on `range_reference_t<R>` already requiring `range<R>`, so just this for short: https://godbolt.org/z/EqWW1n6M1