简体   繁体   English

为什么 C++ 标准容器迭代器会忽略其底层容器的一些模板参数?

[英]Why do C++ std container iterators ignore some template parameters of their underlying container?

Here is a specific example.这是一个具体的例子。 In the code below, I would have expected a compilation error like "cannot assign value of type std::map< int, int, cmp >::iterator to variable of type std::map< int, int >::iterator".在下面的代码中,我预计会出现编译错误,例如“无法将 std::map< int, int, cmp >::iterator 类型的值赋给 std::map< int, int >::iterator 类型的变量” . However, I am able to compile the code without any issues (g++ C++20 Wall).但是,我能够毫无问题地编译代码(g++ C++20 Wall)。 Thanks for help.感谢帮助。

#include <map>

struct cmp {
    bool operator()(const int a, const int b) const { return a > b; }
};

int main(int argc, char *argv[]) {

    std::map<int, int> m1;
    std::map<int, int>::iterator m1_it = m1.begin();

    std::map<int, int, cmp> m2;
    std::map<int, int, cmp>::iterator m2_it = m2.begin();

    // Why do these work?
    m1_it = m2.begin();
    m2_it = m1.begin();

    return 0;
}

Standard sets few constraints on iterator types and just impose some behaviours.标准对迭代器类型几乎没有限制,只是强加了一些行为。

In particular:尤其是:

  • they don't have to be in namespace std .他们不必在namespace std中。 So T* might be a valid iterator for std::vector<T> .所以T*可能是std::vector<T>的有效迭代器。

  • they don't have to have same template parameters than their container.它们不必具有与其容器相同的模板参数。 For above example T* might be an iterator for std::vector<T, Allocator> for any Allocator .对于上面的示例, T*可能是任何Allocatorstd::vector<T, Allocator>的迭代器。

Whereas, indeed, it is less type safe, less template parameter allows less instantiations (faster compilation, less generated similar code, ...).事实上,它的类型安全性较低,模板参数越少,实例化就越少(编译速度越快,生成的类似代码越少……)。

Notice that your code might not compile for compilers/libraries which uses all template parameters for their iterators.请注意,您的代码可能无法针对将所有模板参数用于其迭代器的编译器/库进行编译。

One practical reason is that this might lead to smaller executables.一个实际的原因是这可能会导致更小的可执行文件。 Your two map types can share one iterator type, so all the iterator functions are also shared.你的两个 map 类型可以共享一个迭代器类型,所以所有的迭代器函数也是共享的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM