Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

templates - C++ extract kth element of each tuple in a tuple of tuples

I'm trying to form a std::array out of the ith index of each tuple in a tuple of tuples, however I get the compile error below. I would like to get std::array {2,4,7} in the below example. Source being built using a C++17 compiler.

template<size_t Idx, typename tuple_t>
constexpr auto get_array_from_tuple(tuple_t&& tuple)
{
    constexpr auto get_array = [&](auto&& ... x)
    {  
      return std::array{std::forward<decltype(x)>(std::get<Idx>(x)...)};      
    };
    return std::apply(get_array, std::forward<tuple_t>(tuple));
}

int main()
{
    std::tuple t = {std::tuple(1,2,3), std::tuple(3,4,5), std::tuple(6,7,8)};
    std::array a = get_array_from_tuple<1>(t);
}

Compiler error

<source>: In function 'constexpr auto get_array_from_tuple(tuple_t&&)':
<source>:9:32: error: parameter packs not expanded with '...':
    9 |     constexpr auto get_array = [&](auto&& ... x)
      |                                ^~~~~~~~~~~~~~~~~
   10 |     {
      |     ~                           
   11 |       return std::array{std::forward<decltype(x)>(std::get<Idx>(x)...)};
      |       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   12 |     };
      |     ~                           
<source>:9:32: note:         'x'

Update: The following modification based on hint in the comments seems to work.

template<size_t Idx, typename tuple_t>
constexpr auto get_array_from_tuple(tuple_t&& tuple)
{
    constexpr auto get_array = [&](auto&& ... x)
    {  
      return std::array{std::get<Idx>(x)...};      
    };
    return std::apply(get_array, std::forward<tuple_t>(tuple));
}

as does the following:

template<size_t Idx, typename tuple_t>
constexpr auto get_array_from_tuple(tuple_t&& tuple)
{
    constexpr auto get_array = [&](auto&& ... x)
    {  
      return std::array{std::forward<decltype(std::get<Idx>(x))>(std::get<Idx>(x))...};      
    };
    return std::apply(get_array, std::forward<tuple_t>(tuple));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...