gpt4 book ai didi

c++ - 无法完全理解模板模板参数的工作原理

转载 作者:搜寻专家 更新时间:2023-10-31 01:12:02 24 4
gpt4 key购买 nike

我正在阅读现代 C++ 设计,但无法完全理解模板模板参数的工作原理。

例如本文给出的http://www.informit.com/articles/article.aspx?p=376878我们可以使用 type 和 containers 的模板参数创建 Stack 。

如果我们只使用类型和容器作为模板 Stack 的参数,那么它可能会产生一些问题,例如

template <typename T, class Cont>
class Stack;

template <typename> class List;
Stack<int, List<int> > aStack1; // OK
Stack<double, List<int> > aStack2; // legal, not OK
Stack<std::string, Deque<char *> > aStack3; // error!

在上面的代码中,我可以理解 aStack1 很好,aStack2 和 aStack3 是问题,因为如果 Stack 元素类型和容器元素类型之间的类型不兼容。

根据文章,如果我们使用模板模板参数,这可以解决

template <typename T, template <typename> class Cont>
class Stack;

Stack<int,List> aStack1;
Stack<std::string,Deque> aStack2;

这里我的疑惑是Deque怎么知道它的元素类型是std::string或者List元素类型是int???这是通过模板参数推导完成的吗?

这里我们创建一个类型为 T 的双端队列。如果我们将堆栈定义为

template <typename T,template U, template <typename> class Cont>
class Stack;

那我们如何实例化Stack

   Stack<std::string,int,Deque> // will this work????

最佳答案

My doubt here is how can Deque knows that its element type is std::string or List element type is int???Is this done by template argument deduction?

不,您在 Stack 的实现中显式实例化了类模板,它很可能被实现为:

template <typename T, template <typename> class Cont>
class Stack
{
Cont<T> _container; //here you use `T` as template argument to `Cont`

Cont<int> _ints; //you can do even this if you need a containter of int.
//though in this case you don't need this.

public:
void push(T const & data)
{
_container.push_back(data);
}
//etc
};

关于c++ - 无法完全理解模板模板参数的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14120584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com