当我直接构造一个向量作为参数与使用定义为变量的向量时,情况有所不同,有人可以解释为什么吗?
#include <cstdlib>
#include <iostream>
#include <ostream>
#include <ranges>
#include <vector>
using namespace std;
template <std::ranges::range R>
std::ranges::borrowed_iterator_t<R> random_elt(R&& r) {
auto it = r.begin();
for (size_t i = 0; i < ::rand() % std::ranges::size(r); i++) {
it++;
}
return it;
}
int main() {
std::vector<int> v{1, 2, 3};
// This is fine.
cout << *random_elt(v) << endl;
// Surely this should be the same?
cout << *random_elt(std::vector<int>({1, 2, 3})) << endl;
}
错误:
$ g++ -o main main.cpp -std=gnu++23
main.cpp: In function ‘int main()’:
main.cpp:24:13: error: no match for ‘operator*’ (operand type is ‘std::ranges::borrowed_iterator_t<std::vector<int> >’)
24 | cout << *random_elt(std::vector<int>({1, 2, 3})) << endl;
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~