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 does this technique have?
I’ve seen some examples of C++ using template template parameters (that is templates which
Share
I think you need to use template template syntax to pass a parameter whose type is a template dependent on another template like this:
Here,
His a template, but I wanted this function to deal with all specializations ofH.NOTE: I’ve been programming c++ for many years and have only needed this once. I find that it is a rarely needed feature (of course handy when you need it!).
I’ve been trying to think of good examples, and to be honest, most of the time this isn’t necessary, but let’s contrive an example. Let’s pretend that
std::vectordoesn’t have atypedef value_type.So how would you write a function which can create variables of the right type for the vectors elements? This would work.
NOTE:
std::vectorhas two template parameters, type, and allocator, so we had to accept both of them. Fortunately, because of type deduction, we won’t need to write out the exact type explicitly.which you can use like this:
or better yet, we can just use:
UPDATE: Even this contrived example, while illustrative, is no longer an amazing example due to c++11 introducing
auto. Now the same function can be written as:which is how I’d prefer to write this type of code.