我一直在编写一些采用名为 的模板的函数It,该模板应该是一个迭代器。然后我使用It::value_type来实现某些功能。这对于我尝试过的大多数容器都有效,但对于std::array. 如果我确实使用了,std::array我会收到错误
error: \xe2\x80\x98long unsigned int*\xe2\x80\x99 is not a class, struct, or union type\nRun Code Online (Sandbox Code Playgroud)\n所以我看到了问题, 的迭代器std::array只是一个指针,这对我来说是有意义的。因此它没有::value_type定义。但是我怎样才能制作我的模板化代码,以便它适用于std::array和std::vector等std::list?
我做了一个 MWE,其中的函数只是一个愚蠢的病态例子,显示了我的问题
\n#include <vector>\n#include <iostream>\n#include <array>\n\ntemplate <class It>\nvoid print_accumulate(It first, It last) {\n typename It::value_type result{}; // What do I write here??\n while (first != last) {\n result += *first;\n ++first;\n }\n std::cout << result << "\\n";\n}\n\nint main() {\n std::vector<size_t> v = {1, 2, 3, 4, 5}; /* Replacing with std::array<size_t, 5> gives error */\n print_accumulate(v.begin(), v.end());\n}\nRun Code Online (Sandbox Code Playgroud)\n上面的内容对于我尝试过的几乎每个容器都适用,vector,list等。但是,当我尝试通过替换set来运行代码时,我收到了我给出的错误消息。std::vector<size_t>std::array<size_t, 5>
提前致谢!
\ntemplate <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";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |