c++ - 使用模板模板参数时出错

标签 c++ templates stl template-templates

我自己正在研究 CPP 模板,在尝试为一个类设置模板参数模板时卡住了。我在尝试实例化类成员时遇到错误。

#pragma once

#include "stdafx.h"
# include <list>

template<class type, template<type> class T>
class stack
{
private:
    int count;
    int size;
    T<type> st;

public:
    stack(size_t size):size(100), count(-1){ }
    void push(type elem);
    type pop();

};

template<class type, template<type> class T>
void stack<type, T>::push(type elem)
{
    if (count < (size - 1))
    {
        st.push_back(elem);
        count++;
    }
    else
    {
        cout << "Elements cannot be added to the internal stack" << endl;
    }
}

template<class type, template<type> class T>
type stack<type, T>::pop()
{
    if (count < 0)
    {
        cout << "Stack is empty," << endl;
    }
    else
    {
        T elem = st.back();
        st.pop_back();
        count--;
        return elem;
    }
}

void test_stack_class()
{
    stack<int, list> s1(10);
    /*s1.push(vec);
    s1.push(22);
    s1.push(40);
    s1.push(12);
    s1.push(7);
    cout << "Stacks pops: " << s1.pop() << endl;
    cout << "Stacks pops: " << s1.pop() << endl;
*/

}

请帮助我克服这个错误并尝试解释一下。我认为我对模板的理解有些薄弱,以至于即使在引用了许多在线网站之后我也无法解决问题。

更新:- 我收到了这些错误。

Severity    Code    Description Project File    Line    Suppression State
Error   C2514   'stack': class has no constructors  templates_learning  c:\users\bhpant\source\repos\templates_learning\templates_learning\stack.h  58  
Error   C2993   'type': illegal type for non-type template parameter '__formal' templates_learning  c:\users\bhpant\source\repos\templates_learning\templates_learning\stack.h  12  
Error (active)  E0999   class template "std::list" is not compatible with template template parameter "T"   templates_learning  c:\Users\bhpant\source\repos\templates_learning\templates_learning\stack.h  58  
Error   C3201   the template parameter list for class template 'std::list' does not match the template parameter list for template parameter 'T'    templates_learning  c:\users\bhpant\source\repos\templates_learning\templates_learning\stack.h  58  

最佳答案

您错误地声明了模板模板参数。改变

template<class type, template<type> class T>
class stack

template<class type, template<typename> class T>
class stack

顺便说一句:std::list 有两个模板参数(第二个有默认值),但是T 只有一个;他们不匹配。自 C++17 以来它工作正常,但如果您的编译器不能很好地支持 C++17,您可能必须使用参数包来解决问题。

template<class type, template<typename...> class T>
class stack

关于c++ - 使用模板模板参数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50656291/

相关文章:

c++ - STL - 在 <algorithm> 中使用成员函数或函数?

c++ - getline() 直到输入 C++ 结束

c++ - 如何将从模板参数派生的编译时信息添加到模板?

c++ - 使用模板类型参数时出错

C++ STD 容器:std::vector - 有没有办法清除 vector 并保留存储分配?

c++ - map 中的两个键值可以相同吗

c++ - 避免 C++ 类方法中的代码重复?

c++ - 如何在 cmake 中使用 QML_ELEMENT

c++ - 为什么只能在头文件中实现模板?

模板中的django shuffle