【问题标题】:How to make sure an iterator template parameter has the same data type as the template parameter of a template class如何确保迭代器模板参数与模板类的模板参数具有相同的数据类型
【发布时间】:2014-08-21 01:25:06
【问题描述】:

对不起,标题太长了...请让我知道如何使它变得更好...

我有一个模板类:

template <typename T>
class Example {
    ...
    template <typename Iterator>
    void add(const Iterator begin, const Iterator end);
    ...
};

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

另一个相关问题:

这个STL向量构造函数是如何实现的

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

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

编辑:

有编译时解决方案吗?

【问题讨论】:

  • 类似static_assert(is_same&lt;decltype(*begin), T&gt;::value)的东西
  • @IgorTandetnik 可能需要decay

标签: c++ templates stl iterator


【解决方案1】:

您可以执行以下操作:

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");
}

【讨论】:

  • 但这在运行时有效。编译时有解决办法吗?
  • @Zhi: 是编译时检查。
  • @Zhi A static_assert 是一个编译时断言。
  • @0x499602D2 不知道。谢谢!
【解决方案2】:

您可以这样做以确保 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);

这不是。

【讨论】:

    猜你喜欢
    • 2021-03-08
    • 2014-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2018-06-25
    • 2014-01-29
    相关资源
    最近更新 更多