c++ - 如何帮助模板类型推断

标签 c++ templates

我有一个抽象基类:

template<class T>
class Iterator
{
  public:
    virtual T operator*() = 0;
    ...
};

我有一个具体的子类

template<class T,
         template<class, class> class Col,
         class Alloc = std::allocator<T>>
class StdIterator final: virtual public Iterator<T>
{
    typedef typename Col<T, Alloc>::iterator std_iterator;
    std_iterator b, e;
  public:
    StdIterator(Col<T, Alloc>);
    StdIterator(std_iterator, std_iterator);
    T operator*() const override;
    ...
};

在调用点,我有类似 StdIterator<int, std::vector> x (a_std_vector) 的代码. 我怎样才能将调用站点更改为简单的 StdIterator<std::vector<int>>> x (a_std_vector) , 并让它绑定(bind) T基于 std::vector 的模板参数?我仍然需要将 T、Col 和 Alloc 全部绑定(bind)在类的体内。

除此之外,我拥有的代码仅适用于 std::vectors,不适用于 std::sets 等。我试图获得该功能(使用可变参数类模板),但我什至无法获得它进行编译。

最佳答案

标准容器有 value_type typedef,所以你可以使用类似的东西:

template<class C>
class StdIterator final: virtual public Iterator<typename C::value_type>
{
    typedef typename C::iterator std_iterator;
    // your stuff
};

关于c++ - 如何帮助模板类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26942696/

相关文章:

c++ - 使用模板重载运算符,但防止重新定义

c++ - 将结构更改为类(以及其他类型更改)和 ABI/代码生成

c++ - 在 C++ 中先验未知子类类型的模型类/子类

c++ - 绑定(bind)到已销毁堆栈变量的 const 引用的生命周期

c++ - 有没有办法通过原型(prototype)设计将类型 int 更改为类型 char?

c++ - C++ 模板的函数解析是如何完成的?

django - {{ services|pprint|safe }} 中的 '|' 在 django 中意味着什么?

c++ - 枚举值的编译时列表

c++ - QT 5 [ 错误 : QtGui/QApplication: No such file or directory]

c++ - 区分用户和非用户类型和模板特化