小编Fra*_*nkM的帖子

为什么在传递 std::vector 时不能为 std::span<T> 推导 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
查看次数