C++ std::get fails

后端 未结 4 1668
抹茶落季
抹茶落季 2021-01-12 20:48

How do I use a variable to index into a tuple using std::get<>? I have the following code:

#include 
#include 
using n         


        
4条回答
  •  深忆病人
    2021-01-12 21:37

    #include 
    
    template
    auto index_over( std::index_sequence ) {
      return [](auto&& f)->decltype(auto){
        return decltype(f)(f)( std::integral_constant{}... );
      };
    }
    template
    auto index_upto( std::integral_constant ={} ) {
      return index_over( std::make_index_sequence{} );
    }
    template
    auto foreacher( F&& f ) {
      return [f=std::forward(f)](auto&&...args)mutable {
        (void(), ..., void(f(decltype(args)(args))));
      };
    }
    template
    auto count_upto( std::integral_constant ={} ) {
      return [](auto&& f){
        index_upto()(foreacher(decltype(f)(f)));
      };
    }
    

    you can just do:

    #include 
    #include 
    
    int main() {
      std::tuple data(5, 10);
      count_upto<2>()([&](auto I){
        std::cout << "#" << (I+1) << ":" << std::get(data) << "\n";
      });
    }
    

    Live example.

    There is no unbounded recursion in this solution. It does require C++1z -- you can replace the body of foreacher with the using unused=int[]; trick in C++14.

提交回复
热议问题