在 template<class It> 函数中,It 是一个迭代器,我可以使 It::value_type 同时适用于 vector::iterators 和 array::iterators 吗?

Slu*_*ger 3 c++ templates

我一直在编写一些采用名为 的模板的函数It,该模板应该是一个迭代器。然后我使用It::value_type来实现某些功能。这对于我尝试过的大多数容器都有效,但对于std::array. 如果我确实使用了,std::array我会收到错误

\n
error: \xe2\x80\x98long unsigned int*\xe2\x80\x99 is not a class, struct, or union type\n
Run Code Online (Sandbox Code Playgroud)\n

所以我看到了问题, 的迭代器std::array只是一个指针,这对我来说是有意义的。因此它没有::value_type定义。但是我怎样才能制作我的模板化代码,以便它适用于std::arraystd::vectorstd::list

\n

我做了一个 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}\n
Run Code Online (Sandbox Code Playgroud)\n

上面的内容对于我尝试过的几乎每个容器都适用,vectorlist等。但是,当我尝试通过替换set来运行代码时,我收到了我给出的错误消息。std::vector<size_t>std::array<size_t, 5>

\n

提前致谢!

\n

Pio*_*ycz 6

使用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";
}


Run Code Online (Sandbox Code Playgroud)

  • @Slugger如果你想编写可移植且正确的迭代器逻辑,那么不——不是真的。“iterator_traits”对于所有可能是迭代器的类型(包括不能具有成员类型的指针)来说都是可移植的。如果您编写“typename It::value_type”,那么您将自己耦合到迭代器的实现。如果您正在编写自己的容器并且知道该类型具有“value_type”,这可能是有意义的,但在大多数情况下,这会降低通用性、可移植性和正确性 (3认同)