假设我必须使用无法修改的模板:
// cannot modify
template <typename C,typename T>
void foo(C& c,const T& t) {
// ...
std::iota(std::begin(c),std::end(c),t);
// ...
}
#include <vector>
#include <utility>
#include <numeric>
int main()
{
std::vector<std::pair<int,int>> y(5);
foo(y,std::pair<int,int>{1,2});
}
的预期内容y
是{1,2},{2,3},{3,4},{4,5},{5,6}
。
错误是:
In file included from /opt/compiler-explorer/gcc-9.2.0/include/c++/9.2.0/numeric:62,
from <source>:2:
/opt/compiler-explorer/gcc-9.2.0/include/c++/9.2.0/bits/stl_numeric.h: In instantiation of 'void std::iota(_ForwardIterator, _ForwardIterator, _Tp) [with _ForwardIterator = __gnu_cxx::__normal_iterator<std::pair<int, int>*, std::vector<std::pair<int, int> > >; _Tp = std::pair<int, int>]':
<source>:9:14: required from 'void foo(C&, const T&) [with C = std::vector<std::pair<int, int> >; T = std::pair<int, int>]'
<source>:16:34: required from here
/opt/compiler-explorer/gcc-9.2.0/include/c++/9.2.0/bits/stl_numeric.h:94:4: error: no match for 'operator++' (operand type is 'std::pair<int, int>')
94 | ++__value;
| ^~~~~~~~~
Compiler returned: 1
好的,我知道std::pair
没有operator++
,但如果我自己提供一个,我不能将其范围限制为foo
.
当我不允许定义 a 时,如何使用std::iota
容器?std::pair<T,U>
template <typename T,typename U> std::pair<T,U>::operator++