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. 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. Another option might be InIt
to signal that the iterators should not be output iterators.
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
. Combine this with SFINAE and you get something like the following:
#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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With