我一直在撰寫一些采用名為 的模板的函式It,它應該是一個迭代器。然后我將It::value_type用于某些功能。這對我嘗試過的大多數容器都有效,但對于std::array. 如果我確實使用了std::array我會得到錯誤
error: ‘long unsigned int*’ is not a class, struct, or union type
所以我看到了問題, 的迭代器std::array只是一個指標,這對我來說很有意義。因此它沒有::value_type定義。但是,我怎么能讓我的模板代碼,使這個作品std::array和std::vector,std::list等?
我做了一個 MWE,其中的功能只是一個愚蠢的病理例子,顯示了我的問題
#include <vector>
#include <iostream>
#include <array>
template <class It>
void print_accumulate(It first, It last) {
typename It::value_type result{}; // What do I write here??
while (first != last) {
result = *first;
first;
}
std::cout << result << "\n";
}
int main() {
std::vector<size_t> v = {1, 2, 3, 4, 5}; /* Replacing with std::array<size_t, 5> gives error */
print_accumulate(v.begin(), v.end());
}
以上幾乎適用于我嘗試過的每個容器vector、list、set等。 但是,當我嘗試通過替換std::vector<size_t>with來運行代碼時std::array<size_t, 5>,我收到了我給出的錯誤訊息。
提前致謝!
uj5u.com熱心網友回復:
用 iterator_traits
template <class It>
void print_accumulate(It first, It last) {
typename std::iterator_traits<It>::value_type result{}; // use iterator_traits
while (first != last) {
result = *first;
first;
}
std::cout << result << "\n";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/342881.html
上一篇:.htaccess重寫規則到外部域-客戶端IP和HTTP參考
下一篇:c 智能指標c'tor設計說明
