[英]C++ : syntax for passing iterator to a function?
I am making a class which is a kind of container and I would like to make a constructor that can take a "first" and "last" iterator like std::vector and other standard containers. 我正在创建一个类,它是一种容器,我想创建一个构造函数,可以采用像std :: vector和其他标准容器这样的“第一个”和“最后一个”迭代器。 What would be the correct syntax ?
什么是正确的语法? (I want a template a function that can take any first/last iterator types available (like the standard library I think). Thank you very much !
(我想要一个模板,一个可以使用任何第一个/最后一个迭代器类型的函数(比如我认为的标准库)。非常感谢!
As an example, I want something like that : 举个例子,我想要这样的东西:
template<class ...> MyClass(... first, ... last)
But what are the ... ? 但是......是什么?
Thank you very much. 非常感谢你。
Regarding the first answer : I want a specific constructor that takes iterators as argument (because I have already constructors that take values and pointers as arguments) 关于第一个答案:我想要一个特定的构造函数,它将迭代器作为参数(因为我已经有了将值和指针作为参数的构造函数)
EDIT : Is something like this ok ? 编辑:这样的话好吗?
template<class T1, class T2> MyClass(std::iterator<T1, T2> first, std::iterator<T1, T2> last)
The ...
can be whatever you want, it's just a placeholder name for whatever the type will be. ...
可以是你想要的任何东西,它只是一个占位符名称,无论什么类型。 I think you need to read a good book . 我想你需要读一本好书 。
template<class Iter> MyClass(Iter first, Iter last)
Iter
is a common name if the type should represent an iterator. 如果类型应该表示迭代器,则
Iter
是一个通用名称。 Another option might be InIt
to signal that the iterators should not be output iterators. 另一个选项可能是
InIt
,表示迭代器不应该是输出迭代器。
I think that you can do what you want by taking advantage of the fact that std::iterator
's have a member named iterator_category
. 我认为你可以通过利用
std::iterator
有一个名为iterator_category
的成员的事实来做你想做的事。 Combine this with SFINAE and you get something like the following: 将此与SFINAE结合使用,您将获得以下内容:
#include <iostream>
#include <vector>
template <class X>
class my_class {
public:
my_class(X a, X b) {
std::cout << "in my_class(X,X)" << std::endl;
}
template <class Iter>
my_class(Iter a, Iter b, typename Iter::iterator_category *p=0) {
std::cout << "in my_class(Iter,Iter)" << std::endl;
}
};
int
main()
{
char buf[] = "foo";
std::vector<char> v;
my_class<int> one(1, 2);
my_class<char*> two(&buf[0], &buf[3]);
my_class<char> three(v.begin(), v.end());
return 0;
}
This prints: 这打印:
in my_class(X,X)
in my_class(X,X)
in my_class(Iter,Iter)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.