c++ - 模板变量 `list` 不起作用?

标签 c++ templates

我有以下模板类:

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

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

相关文章:

c++ - 为什么此合并排序实现无法正常工作?

c++ - 自动模板参数推导不起作用

C++类错误'const class Number'没有名为 'intValue'的成员

c++ - std::rel_ops 的惯用用法

模板模板的 C++ 构造函数

c++ - 如何获得专用模板以使用成员函数的非专用版本?

c++ - 用作模板参数的 lambda 正文中的右位移位在 GCC 上无法编译

c++ - 动态调度的部分模板特化

c++ - 如何包装 C++11 回调?

c++ - CMake、链接目录和多个 Boost 安装