gpt4 book ai didi

c++ - 实例化一个模板类

转载 作者:行者123 更新时间:2023-11-28 08:17:33 24 4
gpt4 key购买 nike

这是我的代码:

template<typename T, template<typename = T,typename =std::allocator<typename = T> > class Container= std::vector>
class stack
{
public:
Container<T> cont;
stack()
{

}
};

如果我将第一行代码替换为下面的代码,那么它就可以工作了:

template<typename T, template<typename elem= T,typename =std::allocator<elem> > class Container= std::vector>

但我想问一下我读过当你不使用模板类型参数时你可以这样写:<typename=default_type><typename> .还有 T上面的代码在模板模板参数的参数列表中可见 Container (即类型参数 T 在其整个参数化子句中可见)。所以总而言之,我认为它应该有效。但它没有并给出错误:

error: expression '<erroneous-expression> = <erroneous-expression>' is not a constant-expression
error: template argument 1 and 2 are invalid

那么谁能解释为什么我会看到这些错误,什么是错误表达?

最佳答案

当一个模板参数本身就是一个模板时,除了定义模板-模板参数的“模板签名”之外,它自己的模板参数不会在外部模板的上下文中使用或相关。因此,您不需要这两个参数名称,因为它们既不可用也不是必需的。你可以简单地说:

template <typename T, template<typename, typename> class Container = std::vector>
class stack
{
typedef Container<T, std::allocator<T> > CT;
// ...
};

在这里template <typename, typename>只是 Container 的模板签名您期望的模板类。

在 C++11 中,您可以通过使用可变参数模板做得更好并允许使用更通用的容器:

template <typename T, template<typename...> class Container = std::vector> class stack;

[为了完整性:]将默认类型放在模板参数的参数列表中也可以,这意味着您可以稍后省略这些类型(就像您已经做的那样):

template<typename = T, typename = std::allocator<T> > class Container

---> now we can say:

Container<T> x; // use second default argument
Container<> y; // use both default arguments

回答你的问题:你想在

中指定一个默认的 type
 template <typename = T, typename = std::allocator<typename> > class Container
^^^^^^^^^^^^^^^^^^^^^^^^
Error!!

但是std::allocator<typename>不是一种类型——它甚至不是合法的语法。你可以有一个模板参数,它又是一个模板,即 template <typename> = std::allocator ,但这不会被 std::vector 匹配,或者你有一个实际类型:

template <typename = T, typename = std::allocator<T> > class Container
^^^^^^^^^^^^^^^^^
OK, this is a type

关于c++ - 实例化一个模板类 <erroneous-expression>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7206116/

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