【发布时间】:2022-01-10 14:06:47
【问题描述】:
对于一个学校项目,我必须实现 std::vector 但只能使用 C++98 标准。
问题是当我用有符号整数调用它时,大小构造函数和迭代器构造函数相互冲突,所以我想出了这个(我自己的enable_if、is_same 和iterator_traits 实现):
// Size constructor
explicit vector(
size_type count,
const T &value = T(),
const Allocator &alloc = Allocator()
) : _allocator(alloc),
_capacity(count),
_size(count),
_array(_allocator.allocate(_capacity)) {
std::fill(begin(), end(), value);
}
// Iterator constructor
template <
class InputIt
> vector(
InputIt first, InputIt last,
const Allocator &alloc = Allocator(),
typename ft::enable_if< ft::is_same< typename ft::iterator_traits< InputIt >::value_type, T >::value, int >::type = 0
) : _allocator(alloc),
_capacity(std::distance(first, last)),
_size(_capacity),
_array(_allocator.allocate(_capacity)) {
std::copy(first, last, begin());
}
但是现在我对iterator_traits 的实现有一个问题:当我用int 调用它时,它当然不起作用,因为int 没有迭代器成员类型,但是当我查看cppreference 关于 iterator_traits,它说 If Iter does not have all five member types difference_type, value_type, pointer, reference, and iterator_category, then this template has no members by any of those names (std::iterator_traits is SFINAE-friendly) (since C++17) (until C++20) 这意味着在 C++17 之前没有实现检查,那么真正的 std::vector 在 C++11 之前如何检查迭代器的有效性?
这是我在使用 2 ints 调用构造函数时遇到的编译器错误:
/home/crochu/Documents/42/ft_containers/iterator_traits.hpp:22:20: error: type 'int' cannot be used prior to '::' because it has no members
typedef typename Iter::difference_type difference_type;
^
/home/crochu/Documents/42/ft_containers/vector.hpp:78:55: note: in instantiation of template class 'ft::iterator_traits<int>' requested here
typename ft::enable_if< ft::is_same< typename ft::iterator_traits< InputIt >::value_type, T >::value, int >::type = 0
^
/home/crochu/Documents/42/ft_containers/main.cpp:19:20: note: while substituting deduced template arguments into function template 'vector' [with InputIt = int]
ft::vector< int > v(5, 42);
^
In file included from /home/crochu/Documents/42/ft_containers/main.cpp:13:
In file included from /home/crochu/Documents/42/ft_containers/ft_containers.hpp:15:
/home/crochu/Documents/42/ft_containers/iterator_traits.hpp:23:20: error: type 'int' cannot be used prior to '::' because it has no members
typedef typename Iter::value_type value_type;
^
/home/crochu/Documents/42/ft_containers/iterator_traits.hpp:24:20: error: type 'int' cannot be used prior to '::' because it has no members
typedef typename Iter::pointer pointer;
^
/home/crochu/Documents/42/ft_containers/iterator_traits.hpp:25:20: error: type 'int' cannot be used prior to '::' because it has no members
typedef typename Iter::reference reference;
^
/home/crochu/Documents/42/ft_containers/iterator_traits.hpp:26:20: error: type 'int' cannot be used prior to '::' because it has no members
typedef typename Iter::iterator_category iterator_category;
^
5 errors generated.
【问题讨论】:
-
你应该为基本类型实现 ft::iterator_traits 特化。
-
@S.M.我考虑过,但我想知道是否有更优雅的方法来做到这一点,并且这也适用于类(即使对于向量的情况它也没有用)
标签: c++ stl iterator containers c++98