c++ - 使用 STL 迭代器的模板构造器

标签 c++ templates constructor

我正在编写一个哈希表,但遇到了困难。我想用标准容器( vector 、列表等)的内容初始化它,比如 map :
map <string,int> m(a.begin(),a.end())
我有以下类定义:template <class key,class val,class hashik=std_hash> class hash_table .
我定义了一个构造函数:

template <template <class> class C> hash_table(typename C<pair <key,val> >::iterator first,typename C<pair <key,val> >::iterator last)
{
    init();
    for(pair <key,val>* it=first;it!=last;++it)
        this->operator[](it->first)=it->second;
}

但是它不编译。 没有匹配的调用函数。例如:

vector <pair <string,int> > a;
...
hash_table <string,int> m(a.begin(),a.end()); //compilation error

我做错了什么?您可以推荐我阅读哪些有关模板的书籍?

最佳答案

您试图对您将接受的类型过于具体。要记住的关键是模板只要编译就可以匹配任何东西。如果我正确地破译了你的代码,你就有了这样一个类:

template <typename K, typename V> hash_table { /* ... */ };

这声明了一个哈希表,其键类型为 K,值类型为 V。要编写一个接受来自 map 的元素的构造函数,请声明该构造函数,使其也是一个模板:

template <typename Iter>
hash_table(Iter first, Iter last)
{
    init();
    for (Iter it = first; it != last; ++it)
        this->operator[](it->first)=it->second;
}

这将自动匹配任何可以取消引用以获取 firstsecond 成员的迭代器。在标准容器中,包括 mapmultimap 和它们的 unordered_ 同类。这应该足以让您入门。

另请注意,当您需要不知道如何拼写的类型时,例如复杂的函数指针或 lambda(您根本不会拼写),这是一个有用的技巧。

关于c++ - 使用 STL 迭代器的模板构造器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16064898/

相关文章:

JavaScript:构造函数可以创建 documentElement 对象吗?

c++ - CreateFileMapping() 名称

c++ - OpenGL 纹理占用太多内存

c++ - 创建模板化对象时替代工厂模式 - C++

c++ - 为什么 Visual Studio C++ 编译器拒绝将枚举作为模板参数?

Java Lombok : Omitting one field in @AllArgsConstructor?

c++ - 为什么此代码在具有多字节字符集但不具有 unicode 字符集的 visual studio 中完美运行?

c++ - 初始化对象数组

模板内 C++ value_type::second_type 编译器错误

c++ - 我可以在不分配内存或复制数据的情况下构造一个对象吗?