3

我有以下模板类:

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>为 typeint时,它​​可以工作。问题是什么?

4

2 回答 2

0

的参数 template在编译时解析。

模板参数必须是常量表达式、函数/对象/静态成员的地址或对象的引用。

我想你正在寻找这个:

template <class T,list<int> &t> 
class Tops
{
private:
    list<stack<T>> tops;
public:
    list<stack<T> > getTops() {

    }
};
于 2013-07-27T17:02:04.580 回答
0

更改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

于 2013-07-27T17:05:00.920 回答