2014-12-04 116 views
2

我已存儲迭代器其他容器如下的容器:推斷類型在lambda參數C++ 11

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

請注意,雖然該示例使用具體類型,但我的實際使用案例是在模板代碼中,其中實際類型未知。

+0

在上面的例子中,我可以猜出類型。但如果容器是從其他類返回的,我知道它是一對。但不是其基礎類型。和lambdas不能採取模板 – Pogo 2014-12-04 07:52:41

+0

我的第一個猜測可能會像'my_group_container_t :: value_type'可能? – greatwolf 2014-12-04 07:55:36

+0

我試圖根據你的意見澄清這個問題。如果您不喜歡編輯,請隨時改進或回滾。 – Angew 2014-12-04 08:05:07

回答

3

如果你想成爲通用的,你有幾種選擇:

  1. 使用iterator性狀上的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. 使用值類型o F中的容器(直接或推斷):

    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) { ... }) 
    

在所有這些情況下,您可以根據需要修改pairconst和/或&的類型。請注意,在情況2中,該類型很可能已經是一個參考 - 要求返回實際參考的前向(或更好)運算符。

+0

真棒。我有點忘了iterator_traits: - /謝謝你的答案。 – Pogo 2014-12-04 08:07:05

+1

另外,您可以在行之前使用typedef/type來指定名稱,並且可以在已經複雜的行上減少噪音。 – Yakk 2014-12-04 08:07:39

2

在提供的示例中,它是pair_it_t。可以使用std::iterator_traits<It>::value_type來檢索類型。