如何确保迭代器模板形参与模板类的模板形参具有相同的数据类型

How to make sure an iterator template parameter has the same data type as the template parameter of a template class

本文关键字:形参 数据类型 迭代器 何确保 确保      更新时间:2023-10-16

不好意思,标题太长了…请让我知道如何做得更好。

我有一个模板类:
template <typename T>
class Example {
    ...
    template <typename Iterator>
    void add(const Iterator begin, const Iterator end);
    ...
};

如何确保Iterator所指向的数据类型是T

另一个相关问题:

STL vector构造函数

template <class InputIterator>
vector (InputIterator first, InputIterator last, 
    const allocator_type& alloc = allocator_type());

确保InputIterator具有兼容的数据类型作为向量?

编辑:

是否有一个编译时的解决方案?

您可以这样做:

template <typename Iterator>
void add(const Iterator begin, const Iterator end)
{
   static_assert(std::is_same<typename std::iterator_traits<Iterator>::value_type,
                 T>::value, "Iterator must be the same as T");
}

这样做可以确保Iterator所指向的数据类型为T:

template <typename T>
class Example 
{
public:
    void add(const T* begin, const T* end)
    {
    }
};

vector构造函数不确保InputIterator具有与vector兼容的数据类型。它只是分配内存和分配元素。因此,如果InputIterator所指向的数据类型可以隐式地转换为vector类型,则编译成功,这并不能保证正确的赋值行为。否则会报告错误。

char a[3] = {1, 2, 3};
vector<int> ivec(a, a + 2);

可以成功编译。

string str[3] = {"a", "b", "c"};
vector<int> ivec(str, str + 2);

这并不.