c++ template to template parameter

后端 未结 2 341
余生分开走
余生分开走 2021-01-27 05:05

recently i was testing some c++ template codes and i found one mind-boggling error. According to my research on internet in particular stackoverflow, this code is completely val

2条回答
  •  春和景丽
    2021-01-27 05:24

    std::vector, the type being passed in as C, has more than one template parameter. It has the usual element type, but also an allocator. The easiest way to get around this while keeping a list of type arguments is to use a variadic template:

    template class C, typename... Ts> void print(C& c)
                      ^^^^^^^^                   ^^^^^^             ^^^^^^^^
    

    Actually using the individual type arguments is easier done, in most cases, by explicitly specifying them, as in Cheers' answer. If you don't care about the type arguments, feel free to not keep track of them. In the case of a container, you can even get them from just the container type:

    template void print(Container& c) {
        typename Container::value_type t;
    }
    

提交回复
热议问题