首页 文章

模板类中函数的模板参数

提问于
浏览
1

我有这样的情况

template<class T> class Vector {
  T *data;
  uint _size, _counter;
public:
  class Iterator;
  template<template<class> class C> Vector(typename C<T>::Iterator it1,
                                           typename C<T>::Iterator it2) {
    data = NULL;
    _size = _counter = 0;
    for(typename C<T>::Iterator it = it1; it != it2 && it != end(); it++)
      push(*it);
  }
};

这是我自己的Vector类,构造函数模仿了vector的行为(你可以用使用交互器提供的数据范围来构造它),但是要求容器是与正在构造的类型相同类型的模板 . 我收到错误

5.cpp:16:36:错误:没有匹配函数调用'Vector :: Vector(Vector :: Iterator,Vector :: Iterator)'5.cpp:16:36:注意:候选者是:包含在文件中从5.cpp:2:0:5.hpp:17:37:注意:模板类typedef CC> Vector :: Vector(typename C :: Iterator,typename C :: Iterator)5.hpp:17:37:note :模板参数推导/替换失败:5.cpp:16:36:注意:无法推断模板参数'模板类typedef C C'包含在5.cpp中的文件:2:0:5.hpp:11:3 :注意:Vector :: Vector()[with T = int] 5.hpp:11:3:注意:候选者需要0个参数,2个提供5.hpp:7:25:注意:Vector :: Vector(const Vector&) 5.hpp:7:25:注意:候选人需要1个参数,2个提供

在这需要一些帮助 .

1 回答

  • 3

    在:

    template<template<class> class C> Vector(typename C<T>::Iterator it1,
                                               typename C<T>::Iterator it2)
    

    编译器不会从 typename C<T>::Iterator 推断出类型 C ,因为它是所谓的非求义上下文 .

    参见§14.8.2.4从类型[temp.deduct.type]中推导出模板参数:

    4 nondeduced上下文是: - 使用qualified-id指定的类型的嵌套名称说明符 . - 作为template-id的类型,其中一个或多个模板参数是引用模板参数的表达式 .

相关问题