将模板函数传递给std :: for_each

xda*_*liu 2 c++ foreach templates stl functor

我正在尝试编写一个简单的模板函数来打印某个容器的每个元素,而不使用for循环.到目前为止,我有

#include <iostream>
#include <vector>
#include <algorithm>

template <typename T> void print_with_space(T x){
  std::cout << x << ' ';
}

template <typename T> void print_all(T beg, T end){
  std::for_each(beg, end, print_with_space<int>);
  std::cout << '\n';
}

int main(){
  int a[] = {1, 2, 3};
  std::vector<int> v(a, a+3);
  print_all(v.begin(), v.end());
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

代码编译并运行,但只是因为我把print_with_space<int>内部的实现print_all.我想在print_with_space那里有明显的原因,但是代码不能编译.我该怎么做呢?

Rak*_*111 5

您可以使用:

std::for_each(beg, end, [](const typename T::value_type& value) {
    print_with_space(value);
});
Run Code Online (Sandbox Code Playgroud)

T是类型std::vector<>::iterator,这是一个RandomAccessIterator.每个RandomAcessIterator都有一个底层类型,暴露出来value_type.

所以,如果你通过std::vector<int>::iterator,std::vector<int>::iterator::value_type将是一个int.

现在您已经拥有了类型,您可以创建一个lambda,它将在每次迭代时执行.


在C++ 14中,您甚至可以:

//'auto' automatically deduces the type for you
std::for_each(beg, end, [](const auto& value) {
    print_with_space(value);
});
Run Code Online (Sandbox Code Playgroud)