C++11 way to index tuple at runtime without using switch

后端 未结 7 1117
[愿得一人]
[愿得一人] 2020-12-02 10:45

I have a piece of c++11 code similar like below:

switch(var) {
   case 1: dosomething(std::get<1>(tuple));
   case 2: dosomething(std::get<2>(tup         


        
7条回答
  •  时光取名叫无心
    2020-12-02 11:24

    No need to get all cray cray in c++17.

    template 
    inline void runtime_get(Func func, Tuple& tup, size_t idx) {
        if (N == idx) {
            std::invoke(func, std::get(tup));
            return;
        }
    
        if constexpr (N + 1 < std::tuple_size_v) {
            return runtime_get(func, tup, idx);
        }
    }
    

    And runtime tuple_element for fun.

    // Returns a pointer to the type, so the element is not initialized.
    template 
    inline void runtime_tuple_element(Func func, size_t idx) {
        if (N == idx) {
            std::tuple_element_t* ptr = nullptr;
            std::invoke(func, ptr);
            return;
        }
    
        if constexpr (N + 1 < std::tuple_size_v) {
            return runtime_tuple_element(func, idx);
        }
    }
    

提交回复
热议问题