相关疑难解决方法(0)

如何将 std::vector 转换为 std::span?

std::span 构造函数的文档中,没有一个接受 std::vector 。

那么,这段代码(源页面)是如何编译的?

// createSpan.cpp

#include <algorithm>
#include <iostream>
#include <span>
#include <vector>

int main() {

    std::cout << std::endl;
    std::cout << std::boolalpha;

    std::vector myVec{1, 2, 3, 4, 5};
    
    std::span mySpan1{myVec};                                        // (1)
    std::span mySpan2{myVec.data(), myVec.size()};                   // (2)
    
    bool spansEqual = std::equal(mySpan1.begin(), mySpan1.end(),
                                 mySpan2.begin(), mySpan2.end());
    
    std::cout << "mySpan1 == mySpan2: " << spansEqual << std::endl;  // (3)

    std::cout << std::endl;
    
}
Run Code Online (Sandbox Code Playgroud)

即在 (1) 处调用了 std::span 的哪个构造函数?

c++ c++20

13
推荐指数
1
解决办法
1187
查看次数

为什么在传递 std::vector 时不能为 std::span&lt;T&gt; 推导 T ?

在以下 C++20 代码中,将 a 传递std::vector给带有参数的模板化函数std::span<T>会失败,因为显然编译器无法推导出模板参数。我已经用 GCC、Clang 和 MSVC 尝试过了;全部失败。

像这样调用有效:f3(std::span(vi))f3(std::span(vp))

我想知道为什么会失败,因为在我的理解中,std::vector是一个范围,并且std::span有范围的推导指南。

#include <memory>
#include <vector>
#include <span>

void f1(std::span<int> s)
{
}

void f2(std::span<std::shared_ptr<int>> s)
{
}

template<typename T>
void f3(std::span<T> s)
{
}

int main(int argc, char* argv[])
{
    std::vector<int> vi;
    std::vector<std::shared_ptr<int>> vp;

    f1(vi);
    f2(vp);
    f3(vi); // ERROR: no matching function for call to 'f3'
    f3(vp); // ERROR: no matching function for call to …
Run Code Online (Sandbox Code Playgroud)

c++ templates template-argument-deduction c++20 std-span

11
推荐指数
2
解决办法
434
查看次数