问题描述
我正在尝试使用 C++98 实现 std::vector。
而且,我提到了 https://www.cplusplus.com/reference/vector/vector/vector/
因此,在构造函数中,我对向量进行了如下编码。
explicit vector (size_type n,const value_type& val = value_type(),const allocator_type& alloc = allocator_type())
{
...
}
template <class InputIterator>
vector (InputIterator first,InputIterator last,const allocator_type& alloc = allocator_type())
{
...
}
但是,当我在 main 中测试该向量时,它并没有像我想要的那样工作。
int main(void)
{
vector<int> vec(3,100);
}
我想调用 explicit vector (size_type n,const allocator_type& alloc = allocator_type())
,但调用了带有迭代器的构造函数。
所以,我的问题是
很抱歉打扰你,但我真的不知道为什么会这样......
解决方法
实现通常会使用某种类型特征来启用/禁用迭代器版本,具体取决于迭代器类型是否真的是迭代器。
例如,它在概念上类似于:
template <class InputIterator,typename = enable_if_t<IsIterator_v<InputIterator>>
vector(InputIterator first,InputIteratorLast)
(或更正确,以避免重新定义仅在默认模板参数中延迟的模板,如注释和此 notes 下所述:):
// this is more the way it's actually practically implemented
template <class InputIterator,enable_if_t<IsIterator_v<InputIterator>,int> = 0>
vector(InputIterator first,InputIteratorLast)
其中 IsIterator_v
是实现定义的类型特征,用于测试迭代器要求。
因此在您的构造函数示例 vector(3,100)
中,迭代器构造函数版本将不参与重载决议。
在 C++98 中,没有enable_if
,但实现也会使用类似的概念检查。