我需要制作一些特定的构造函数,该构造函数具有两个迭代器:开始迭代器和结束迭代器。
我有一些代码及其作品:
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
class A
{
public:
T a[10];
typename std::vector<T>::iterator itStart, itEnd;
A(typename vector<T>::iterator itStart, typename vector<T>::iterator itEnd):itStart(itStart),itEnd(itEnd){}
void see()
{
int i=0;
while(itStart != itEnd)
{
cout<<*itStart<<endl;
a[i] = *itStart;
itStart++;
i++;
}
}
};
template <typename Iterator>
double Sum( Iterator begin, Iterator end );
int main()
{
cout << "Hello world!" << endl;
vector<int> v;
v.push_back(1);
v.push_back(1);
v.push_back(2);
v.push_back(3);
class A<int> a(v.begin(),v.end());
a.see();
return 0;
}
但是我想使构造函数参数与所有STL容器(如Set,List,Map等)和常规数组(常规指针)一起使用。
那我可以用通用模板方式制作吗?像这样:
template<typename T>
class A
{
public:
iterator<T> itStart, itEnd;
A(iterator<T> itStart, iterator<T> itEnd):itStart(itStart),itEnd(itEnd){}
void see()
{
while(itStart != itEnd)
{
cout<<*itStart<<endl;
itStart++;
}
}
};
我知道上面的代码是错误的,但是我想解释一下我的想法。
当然,我可以重载构造函数,但是我对此太懒了。 STL容器过多。
是否有解决此问题的模板方法?
最佳答案
显然,您需要使迭代器类型为类的模板参数
template<class T, class Iter>
class A
{
Iter first, last;
A(Iter first, iter last):first(first), last(last){}
};
但是现在,显式指定template参数变得不舒服
A<int, vector<int>::iterator > a;
为了避免这种情况,只需创建一个工厂函数
template<class T, class Iter>
A<T, Iter> make_A(Iter first, iter last)
{
return A<T, Iter>(first, last);
}
现在,您可以使用函数来代替直接创建A的对象
auto my_A = make_A<int>(v.begin(), v.end());