What are some uses of template template parameters?

后端 未结 10 1139
无人共我
无人共我 2020-11-22 03:41

I\'ve seen some examples of C++ using template template parameters (that is templates which take templates as parameters) to do policy-based class design. What other uses do

10条回答
  •  借酒劲吻你
    2020-11-22 03:56

    Actually, usecase for template template parameters is rather obvious. Once you learn that C++ stdlib has gaping hole of not defining stream output operators for standard container types, you would proceed to write something like:

    template
    static inline std::ostream& operator<<(std::ostream& out, std::list const& v)
    {
        out << '[';
        if (!v.empty()) {
            for (typename std::list::const_iterator i = v.begin(); ;) {
                out << *i;
                if (++i == v.end())
                    break;
                out << ", ";
            }
        }
        out << ']';
        return out;
    }
    

    Then you'd figure out that code for vector is just the same, for forward_list is the same, actually, even for multitude of map types it's still just the same. Those template classes don't have anything in common except for meta-interface/protocol, and using template template parameter allows to capture the commonality in all of them. Before proceeding to write a template though, it's worth to check a reference to recall that sequence containers accept 2 template arguments - for value type and allocator. While allocator is defaulted, we still should account for its existence in our template operator<<:

    template