简体   繁体   English

交换原始指针和迭代器

[英]Interchanging raw pointers and iterators

I want to declare and implement a function that takes as parameters either pointer or iterators. 我想声明并实现一个以指针或迭代器为参数的函数。 That is to say something like 那就是说像

void run_through(const Itr& begin, const Itr& end)
{
  for (Itr it = begin; it != end; ++it)
    std::cout << *it << " ";
}

And I want this to be callable with either an iterator or a pointer. 我希望可以使用迭代器或指针来调用它。 That is to say something like. 那就是说类似。

int main(int, char**)
{
  int a[] = {3, 1, 4, 1, 5, 9};
  std::vector<int> A(a, a+6);
  std::set<int> B(a, a+6);

  run_through(a, a+6);
  run_through(A.begin(), A.end());
  run_through(B.begin(), B.end());

  return 0;
}

What I'm wondering is if I can declare run_through without any template parameters and have the implementation of run_through in a separate .cpp file. 我想知道的是,是否可以run_through不使用任何模板参数的情况下声明run_throughrun_through在单独的.cpp文件中实现run_through的实现。

I'm pretty sure you can't implement a function that takes either pointers or iterators without using templates. 我敢肯定,如果不使用模板,就无法实现采用指针或迭代器的函数。 While pointers and iterators are essentially implementing the same concept, they are not types where one degrades into another one like the C array to pointer degradation. 尽管指针和迭代器实质上实现了相同的概念,但它们不是那种将其降级为另一个像指针降级的C数组的类型。

The clean solution thus is indeed to use a single template function, for example in C++98: 因此,干净的解决方案确实是使用单个模板函数,例如在C ++ 98中:

template<typename forward_itr>
void run_through(forward_itr begin, forward_itr end)
{
  for (forward_itr it = begin; it != end; ++it)
    std::cout << *it << " ";
}

You can manually specialize a function template, which is what you'd have to do to have the function implementation in a separate source file, however my recommendation would be to put the whole function into a header file and let the compiler deal with it. 您可以手动对功能模板进行专门化处理,这是在单独的源文件中实现功能所必须要做的,但是我的建议是将整个功能放入头文件中,然后由编译器处理。 Modern compilers and linker are pretty good at dealing with this scenario and the avoidance of possible code duplication. 现代的编译器和链接器非常擅长处理这种情况以及避免可能的代码重复。

Just use a template function no need to have the implementation in a separate cpp 只需使用模板功能,无需在单独的cpp中实现

template <class Itr>
void run_through(Itr&& begin, Itr&& end)
{
  for (Itr it = begin; it != end; ++it)
    std::cout << *it << " ";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM