How to make constructor accept all type of iterators?

后端 未结 2 857
梦谈多话
梦谈多话 2020-12-12 03:50

I am creating a custom Vector/ArrayList class. But i´m having troubles creating the iterative version of the constructor. The following code works, but the problem is when i

2条回答
  •  旧巷少年郎
    2020-12-12 04:26

    What you need to do is use SFINAE to constrain the template to only work when the template type is deduced to be an iterator type. Since you do arr_size{ static_cast(end - begin) } to initialize size this means that you expect the iterators to be random access. We can check for that using the iterator_category of std::iterator_traits Doing that gives you

    template::iterator_category, 
                                                std::random_access_iterator_tag>, bool> = true>
    ArrayList(ITER begin, ITER end) : arr_size{ static_cast(end - begin) }, arr_capacity{ arr_size }
    {
        std::uninitialized_copy(begin, end, array = allocator.allocate(arr_size));
        first = array;
        last = array + arr_size - 1;
    }
    

提交回复
热议问题