Nested C++ template parameters for functions

后端 未结 3 1363
再見小時候
再見小時候 2020-12-13 09:20

I want to have a templated function in C++, where one template parameter is itself a template of another template parameter. If that doesn\'t make any sense, take the follow

相关标签:
3条回答
  • 2020-12-13 09:57

    You're better off not doing that at all; consider just templating on the container

    template <typename C>
    void print_container(const C& container)
    {
    
        for(auto v: container)
            std::cout << v << " ";
        std::cout << std::endl;
    }
    

    If you need the stored type in the function, you can use: `typedef typename C::value_type T;

    0 讨论(0)
  • 2020-12-13 10:00

    I am not sure that I understood what you want but you can try this:

    template <typename V>
    void print_vector(V &vec)
    {
        for(auto v: vec)
            std::cout << v << " ";
        std::cout << std::endl;
    }
    ...
    std::vector<double> vec(5);
    ...
    print_vector(vec);
    

    The point here is that usually you don't need construct like template < template V< typename T> > because whole template template V< typename T> can be generalized to type V.

    0 讨论(0)
  • 2020-12-13 10:10

    std::vector has two parameters, type and allocator. Try this

    template <typename T, typename Alloc, template <typename, typename> class V>
    void print_container(V<T, Alloc> &con)
    {
    }
    
    print_container(vec);
    

    This will work for vector, list, etc., but will not work with map, set.

    However, since you use auto you can use C++11 and then you can to this:

    template <typename T, template <typename, typename...> class V, typename... Args>
    void print_container(V<T, Args...> &con)
    

    or

    template <template <typename, typename...> class V, typename... Args>
    void print_container(V<Args...> &con)
    

    and of course most simple way is to do something like

    template<typename C>
    void print_container(C& con)
    

    probably with some checks for deduce, that C is really container.

    template<typename C>
    auto print_container(C& con) -> decltype(con.begin(), void())
    
    0 讨论(0)
提交回复
热议问题