问题描述
我已经看到了一些C ++使用模板模板参数(即以模板为参数的模板)进行基于策略的类设计的示例.这种技术还有什么其他用途?
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 think you need to use template template syntax to pass a parameter whose type is a template dependent on another template like this:
template <template<class> class H, class S>
void f(const H<S> &value) {
}
在这里,H
是模板,但是我希望此函数处理H
的所有特殊情况.
Here, H
is a template, but I wanted this function to deal with all specializations of H
.
注意:我从事c ++编程已经很多年了,只需要一次.我发现它是很少需要的功能(当然,在需要时很方便!).
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!).
我一直在尝试考虑好的例子,说实话,大多数时候这不是必须的,但让我们来设计一个例子.假设std::vector
没有具有typedef value_type
.
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::vector
doesn't have a typedef value_type
.
那么您将如何编写一个可以为vectors元素创建正确类型的变量的函数?这会起作用.
So how would you write a function which can create variables of the right type for the vectors elements? This would work.
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
具有两个模板参数,类型和分配器,因此我们必须接受它们两者.幸运的是,由于类型推导,我们不需要显式写出确切的类型.
NOTE: std::vector
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.
您可以这样使用:
f<std::vector, int>(v); // v is of type std::vector<int> using any allocator
或更妙的是,我们可以使用:
or better yet, we can just use:
f(v); // everything is deduced, f can deal with a vector of any type!
更新:即使这个人为设计的示例,尽管具有说明性,但由于c ++ 11引入了auto
而已不再是一个了不起的示例.现在相同的函数可以写成:
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:
template <class Cont>
void f(Cont &v) {
auto temp = v.back();
v.pop_back();
// Do some work on temp
std::cout << temp << std::endl;
}
这就是我更喜欢编写这种类型的代码的方式.
which is how I'd prefer to write this type of code.
这篇关于模板模板参数有哪些用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!