Produce std::tuple of same type in compile time given its length by a template argument

前端 未结 5 1882
礼貌的吻别
礼貌的吻别 2021-02-13 10:18

In c++, how can I implement a function with an int template argument indicating the tuple length and produce a std::tuple with that length?

E.g.

func<         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-13 10:34

    Using an index_sequence and a helper type alias you can generate the type you want:

    // Just something to take a size_t and give the type `int`
    template 
    using Integer = int;
    
    // will get a sequence of Is = 0, 1, ..., N
    template 
    auto func_impl(std::index_sequence) {
        // Integer... becomes one `int` for each element in Is...
        return std::tuple...>{};
    }
    
    template 
    auto func() {
        return func_impl(std::make_index_sequence{});
    }
    

    It is worth calling out that in the general case you would probably be better with a std::array, (in your case you can't use one), but a std::array can behave like a tuple, similarly to a std::pair.

    Update: since you've made it clear you're working with c++11 and not 14+, you'll need to get an implementation of index_sequence and related from somewhere (here is libc++'s). Here is the C++11 version of func and func_impl with explicit return types:

    template 
    auto func_impl(std::index_sequence) -> std::tuple...> {
      return std::tuple...>{};
    }
    
    template 
    auto func() -> decltype(func_impl(std::make_index_sequence{})) {
      return func_impl(std::make_index_sequence{});
    }
    

提交回复
热议问题