2013-07-08 159 views
0

在如下所示的模板中,如何從另一個更復雜的元組中填充元素?使用另一個元組中的元素填充元組

template<typename... Ts> 
struct foo { 
    std::tuple<std::vector<Ts>...> tuple; 

    foo() { 
    //populate tuple somehow 
    //assume that no vector is empty 
    } 

    void func() { 
    std::tuple<Ts...> back_tuple; // = ... 
    //want to populate with the last elements ".back()" of each vector 
    //how? 
    } 
}; 

我找不到任何元組的push_back機制,所以我不知道如何使用模板循環技巧來做到這一點。此外,我無法找到任何類似於模板的initializer_list來收集我的值,然後傳遞到新的元組中。有任何想法嗎?

回答

3

嘗試這樣:

std::tuple<std::vector<Ts>...> t; 

template <int...> struct Indices {}; 
template <bool> struct BoolType {}; 

template <int ...I> 
std::tuple<Ts...> back_tuple_aux(BoolType<true>, Indices<I...>) 
{ 
    return std::make_tuple(std::get<I>(t).back()...); // !! 
} 

template <int ...I> 
std::tuple<Ts...> back_tuple_aux(BoolType<false>, Indices<I...>) 
{ 
    return back_tuple_aux(BoolType<sizeof...(I) + 1 == sizeof...(Ts)>(), 
          Indices<I..., sizeof...(I)>()); 
}; 

std::tuple<Ts...> back_tuple() 
{ 
    return back_tuple_aux(BoolType<0 == sizeof...(Ts)>(), Indices<>()); 
} 

(魔術發生在線條爲標誌!!

相關問題