我有以下模板类:
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.
关于c++ - 模板变量 `list` 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17900247/