Hızlı yanıt: kod örneği
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, is a template, but I wanted this function to deal with all specializations of .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 doesn't have a . So how would you write a function which can create variables of the right type for the vectors elements? This would work.NOTE: has 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 . Now the same function can be written as:which is how I'd prefer to write this type of code.
template <template<class> class H, class S>void f(const H<S> &value) {}
H
H
std::vector
typedef value_type
template <template<class, class> class V, class T, class A>void f(V<T, A> &v) { // This can be "typename V<T, A>::value_type", // but we are pretending we don't have it T temp = v.back(); v.pop_back(); // Do some work on temp std::cout << temp << std::endl;}
std::vector
f<std::vector, int>(v); // v is of type std::vector<int> using any allocator
f(v); // everything is deduced, f can deal with a vector of any type!
auto
template <class Cont>void f(Cont &v) { auto temp = v.back(); v.pop_back(); // Do some work on temp std::cout << temp << std::endl;}