在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++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)