如果您查看 和 之類的標準演算法std::ranges::fill,std::ranges::generate它們似乎都使用附加引數來推斷其輸出范圍的范圍值型別。例如,由于它的第二個引數,它ranges::fill(v, 10)能夠推斷出值型別。T
但是,當您嘗試定義一個類似的函式但去掉第二個引數時,C 不再能夠推斷出值型別。例如,考慮以下函式:
template<typename T, std::output_range<const T&> R>
void ones(R && r)
{
for (T & value : r) {
value = 1;
}
}
如果您在未明確指定值型別的情況下嘗試呼叫代碼,則代碼將無法編譯:
std::array<int, 3> a;
// ones(a); // does not compile
ones<int>(a); // redundant!
當我嘗試編譯注釋掉的代碼時,出現以下錯誤:
/home/josiest/sandbox/cpp/template-template-range/sketch.cpp: In function ‘int main()’:
/home/josiest/sandbox/cpp/template-template-range/sketch.cpp:19:9: error: no matching function for call to ‘ones(std::array<int, 3>&)’
19 | ones(a);
| ~~~~^~~
/home/josiest/sandbox/cpp/template-template-range/sketch.cpp:9:6: note: candidate: ‘template<class T, class R> requires output_range<R, T> void ones(R&&)’
9 | void ones(R && r)
| ^~~~
/home/josiest/sandbox/cpp/template-template-range/sketch.cpp:9:6: note: template argument deduction/substitution failed:
/home/josiest/sandbox/cpp/template-template-range/sketch.cpp:19:9: note: couldn’t deduce template parameter ‘T’
19 | ones(a);
| ~~~~^~~
有什么方法可以推斷出我缺少的范圍值型別,還是不可能?
uj5u.com熱心網友回復:
聽起來你想要:
template <typename T> requires std::output_range<T, std::ranges::range_value_t<T>>
也許:
template <typename T> requires std::output_range<T, const std::ranges::range_value_t<T> &>
前者期望元素被移動,后者期望它被復制。如果要同時支持兩者,則可以同時使用這兩個約束。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513866.html
上一篇:不同型別名的模板引數推導
下一篇:動態庫的運行時與鏈接時鏈接
