如何使用模板模板参数中默认参数以外的参数进行实例化
我正在努力巩固我对模板模板参数的理解。在C++ 模板完整指南(Vandervoorde、Josuttis)中,他们在第 52 页上有一个示例,我想使用该示例,如下图所示:
(我也在尝试学习如何在 stackoverflow 上使用 Picasa 中的图像,所以如果上面的方法不起作用,这里有一个稍微更详细的方法版本)
书中的原始代码
template <typename T,
template <typename ELEM, typename ALLOC=std::allocator<ELEM> > class CONT=std::vector>
class Stack
{
private:
CONT<T > elems; //Why doesn't CONT<T, ALLOC> elems; compile?
};
不会向您展示如何将其用于不同的分配器。他们确实显示了一个不同的容器:
Stack<int, std::deque> my_deque_stack;
并且在我天真的尝试中:
Stack<int, std::deque<int, std::allocator<int> > > my_deque_int_stack;
我还在私有部分中尝试将 CONT 定义为,
CONT<T, ALLOC>
但这也会生成编译器错误。我想知道使用 Stack 模板的正确语法是什么,我想使用双端队列但想指定不同的分配器。我在这里读到了一些类似的帖子,这些帖子表明周围散布着类型名或模板限定符,我尝试了一些,但似乎找不到神奇的公式。
I'm trying to cement my understanding of template template parameters. In C++ Templates the Complete Guide (Vandervoorde, Josuttis), they have an example on page 52 that I want to use as indicated in this image:
(I'm also trying to learn how to use images from Picasa on stackoverflow so if the above doesn't work, here's a slightly more verbose version)
Original Code from Book
template <typename T,
template <typename ELEM, typename ALLOC=std::allocator<ELEM> > class CONT=std::vector>
class Stack
{
private:
CONT<T > elems; //Why doesn't CONT<T, ALLOC> elems; compile?
};
The don't show you how to use this for a different allocator. They do show a different container as:
Stack<int, std::deque> my_deque_stack;
and in my naivete I tried:
Stack<int, std::deque<int, std::allocator<int> > > my_deque_int_stack;
I also tried in the private section defining CONT as
CONT<T, ALLOC>
but that too generates a compiler error. I'm wondering what the correct syntax is for using the Stack template where I want to use a deque but want to specify a different allocator. I read some similar posts here that indicate sprinkling typename or template qualifiers around and I tried a couple but couldn't seem to find the magic formula.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CONT内部的参数定义实际上并没有被编译器使用。模板-模板参数 CONT 实际上类似于一个函数,它接受 2 个类型输入并返回一个新类型:
并且与普通函数指针声明一样,名称 ELEM、ALLOC 实际上被编译器忽略 。
编译器看到的只是 因此
,您根本不能使用 ALLOC。
那么要解决它吗?好吧,你传递了一个额外的参数!就像普通 C++ 函数中的情况一样:
相应的实际模板声明将是
The parameter definitions inside CONT are actually not used by the compiler. The template-template parameter CONT is actually similar to a function, which takes 2 types input and return a new type:
and like the normal function pointer declarations, the names ELEM, ALLOC are actually ignored by the compiler.
What the compiler sees would be just
Therefore, you cannot use ALLOC at all.
So to solve it? Well, you pass an extra parameter! Just like the case in a normal C++ function:
The corresponding actual template declaration would be