简体   繁体   中英

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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM