模板变量"列表"不起作用?
Template variable `list` doesn't working?
我有以下模板类:
template <class T, list<int> t>
class Tops
{
private:
list<stack<T>> tops;
public:
list getTops() {
}
};
它不编译为:illegal type for non-type template parameter 't'
,
第6行:template <class T, list<int> t> class Tops
。
当我将list<int>
更改为类型int
时,它就工作了。问题出在哪里?
将template <class T, list<int> t>
更改为template <class T, list<int> &t>
:
template <class T, list<int> &t>
^^^ //note &t
class Tops
{
private:
list<stack<T>> tops;
public:
list getTops() {
}
};
不能这样做的原因是,在编译时无法解析和替换非常量表达式。它们可能在运行时发生变化,这需要在运行时生成一个新模板,这是不可能的,因为模板是一个编译时概念。
以下是标准允许的非类型模板参数(14.1[temp.param]p4):
A non-type template-parameter shall have one of the following
(optionally cv-qualified) types:
- integral or enumeration type,
- pointer to object or pointer to function,
- reference to object or reference to function,,
- pointer to member.
来源答案:https://stackoverflow.com/a/5687553/1906361
template
的参数在编译时解析。
模板参数必须是常量表达式、函数/对象/静态成员的地址或对象的引用。
我想你在找这个:
template <class T,list<int> &t>
class Tops
{
private:
list<stack<T>> tops;
public:
list<stack<T> > getTops() {
}
};
相关文章:
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 链接列表中的所有节点都相同,似乎插入不起作用
- 双链接列表添加元素不起作用,不知何故它总是保持为空
- 对列表迭代器指向的对象不起作用的引用
- 使用.txt文件填充 STL 列表不起作用
- 合并两个排序的列表 - 不起作用
- 为什么此代码用于单个链接列表不起作用
- 没有临时数组的列表初始化 - 在 GCC 中不起作用
- 将列表元素移动到列表末尾的函数多次不起作用
- 在声明节点创建链接列表时,为什么静态内存分配不起作用
- C++ 列表不起作用
- 使用引用遍历链接列表不起作用
- 使用初始化列表的 POD 类型初始化不起作用
- 基于双重链接列表不起作用的Deque实施
- C++迭代时删除列表成员:标准解决方案不起作用
- 标准::列表::擦除不起作用
- 链接列表打印不起作用.
- QML XML 列表视图不起作用
- 尝试使用值初始化列表,但在使用变量创建大小时不起作用
- GCC 4.8.1 中的C++11:复制构造函数的列表初始化不起作用