c++ - 推导 C++11 中 lambda 参数的类型

标签 c++ c++11 lambda

我有一个容器,它将迭代器存储到其他容器,如下所示:

typedef int my_id;    //id
typedef std::set<my_id>  my_group_t;   //group containing ids
typedef typename  my_group_t::iterator  my_group_it_t;    //group iterator

std::pair < my_group_it_t, my_group_it_t >  pair_it_t;  //pair (generally begin,end)
typedef std::vector<  pair_it_t >  my_group_container_t;


my_group_container_t   my_group_container; // (FILL the Container and group with some values)
//print the values using lambdas

auto x = my_group_container.begin();   
auto y = my_group_container.end();

//x is iterator to the vector, similarly y. 

//note that x and y when dereferenced give the pairs of iterators
std::for_each (x, y, [](**xxxx**   pair) -> void {

          auto xx = x.first;    //get first iterator pair
          auto yy = x.second;  //get second iterator pair

      } 

配对的类型应该是什么? xxxx。我知道 lambda 不能在 C++11 中模板化,但我不确定如何在此处使用 decltype

 //I can do this:
  for (; x!=y; ++x) {
    auto xx = x->first;
    auto yy = x->second;
    std::copy(xx,yy,std::ostream_itearator<..> (std::cout, "\n");
  }

请注意,虽然示例使用具体类型,但我的实际用例是在模板代码中,其中真实类型未知。

最佳答案

如果您想通用,您有多种选择:

  1. x 类型上使用迭代器特征:

    std::for_each(x, y, [](std::iterator_traits<decltype(x)>::value_type pair) { ... })
    
  2. 使用*x的返回类型:

    std::for_each(x, y, [](decltype(*x) pair) { ... })
    
  3. 使用容器的值类型(直接或推导):

    std::for_each(x, y, [](my_group_container_t::value_type pair) { ... })
    std::for_each(x, y, [](decltype(my_group_container)::value_type pair) { ... })
    
  4. 如果您确实知道类型(如示例中所示),您当然可以直接使用它:

    std::for_each(x, y, [](pair_it_t pair) { ... })
    

在所有情况下,您都可以根据需要使用 const 和/或 & 修饰 pair 的类型。请注意,在情况 2 中,该类型很可能已经是一个引用 - 需要前向(或更好)运算符来返回实际引用。

关于c++ - 推导 C++11 中 lambda 参数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27288633/

相关文章:

linq - 使用 Linq 或 Lambda 表达式的 SQL 之间的等效语句

Python Tkinter : Bind function to list of variables in a for-loop

c++ - Qt LEFT CTRL键代码

c++ - 内存布局问题

c++ - 将多个参数传递给线程函数 c++11

c++ - 无法使用 unique_ptr 和 deleter 进行编译

c++ - 是否可以在 C++11 中指定枚举的位宽?

c++ - 测试整数类型是有符号还是无符号的宏

c++ - 如何正确终止 dll 中的挂起线程?

C++11 Lambda 表达式作为回调函数