[英]Can you help me understand this C++ template code?
Hya, HYA,
Can anyone please tell me how this thing is working? 任何人都可以告诉我这件事是如何工作的?
template <typename T,
template <typename ELEM> class CONT = std::deque >
class Stack {
private:
CONT<T> elems; // elements
public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element
bool empty() const { // return whether the stack is empty
return elems.empty();
}
};
What i don't understand is this : template class V or say this "template class CONT = std::deque" 我不明白的是:模板类V或说这个“模板类CONT = std :: deque”
i visualize this as 我认为这是
template <class>
class CONT = std::deque // here CONT is templatized class declaration.
but what pesters me is , how can we assign something to class name CONT , rather than writing its definition (which i've done till this time): 但是让我感到困惑的是,我们如何为类名CONT分配一些东西,而不是写出它的定义(直到这个时候我已经完成了):
template <class>
class CONT{
//def
}
one more thing : 还有一件事 :
template <class> // why its only class written in angle bracket there should be also be name
like : template<class ty>
Thanks a lot , any help is very appreciated) 非常感谢,非常感谢任何帮助)
It's not an object assignment. 这不是对象分配。 It's just syntax in a template specifier to specify what the default type argument should be if one is not provided. 它只是模板说明符中的语法,用于指定未提供默认类型参数的默认类型参数。 It's not a definition for that type. 它不是该类型的定义。
What i don't understand is this : template class V 我不明白的是:模板类V.
There is no such line in your question, so I can't help with that. 你的问题中没有这样的界限,所以我无能为力。
template< template <typename ELEM> class CONT = std::deque >
class Stack
This is a declaration of a template template parameter. 这是模板模板参数的声明。 You pass a template into the Stack
template, and then Stack
can use it internally. 您将模板传递到Stack
模板,然后Stack
可以在内部使用它。
The = std::deque
part is a default value, in case you leave the CONT parameter unspecified. = std::deque
部分是默认值,以防您未指定CONT参数。 ( std::deque
is a predefined template.) ( std::deque
是一个预定义的模板。)
However, this will not work, because std::deque
takes two arguments. 但是,这不起作用,因为std::deque
有两个参数。 This will work: 这将有效:
template< template <typename ELEM, typename ALLOC> class CONT = std::deque >
class Stack
However ELEM
and ALLOC
do not actually name anything; 但ELEM
和ALLOC
实际上没有任何名称; they exist merely to clarify what the parameter list of the required template is. 它们的存在仅仅是为了阐明所需模板的参数列表是什么。 So, you can omit them: 所以,你可以省略它们:
template< template <typename, typename> class CONT = std::deque >
class Stack
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.