3

这是一个示例代码:

#include <stack>
#include <cstddef>

template <std::size_t N,
         template <class> class Stack = std::stack
         >   
class Tower : protected Stack<int>
{   
    public:
        Tower() : Stack<int>(N)
        {   
        }   
};  


int main(int argc, char **argv)
{   
    Tower<5L> tower1();
} 

而且我看到编译器(gcc)不高兴:

file.cpp: In function 'int main(int, char**)':
file.cpp:18:11: error: type/value mismatch at argument 2 in template parameter 
list for 'template<long unsigned int N, template<class> class Stack> class Tower'
file.cpp:18:11: error: expected a template of type 'template<class> class Stack',
got 'template<class _Tp, class _Sequence> class std::stack'
file.cpp:18:21: error: invalid type in declaration before ';' token

标准堆栈容器具有以下形式:

template <class Type, class Container = deque<Type> > class stack;

这意味着我应该在这里只传递一个模板参数!

关于如何解决这个问题的任何想法?谢谢

4

3 回答 3

4

'template<class> class Stack', got 'template<class _Tp, class _Sequence> class std::stack' shows the problem.

Here is what std::stack looks like

template<
    class T,
    class Container = std::deque<T>
> class stack;

As you can see there is a second parameter.

Adding:

#include <deque>
template <std::size_t N,
         template <class T, class = std::deque<T>> class Stack = std::stack
         >   

should make it compile.

于 2012-04-07T21:31:45.580 回答
4

std::stack has more than one template argument. Therefore, it can't be used in your case. You can work around this in C++11 with template typedefs.

template <typename T>
using stack_with_one_type_parameter = std::stack<T>;

template <std::size_t N,
     template <class> class Stack = stack_with_one_type_parameter
     >
class Tower;
于 2012-04-07T21:34:02.607 回答
2

谢谢,效果很好。这是对我的代码的修改:

#include <stack>
#include <queue>
#include <cstddef>

template <std::size_t N,
         class T,
         template <class, class> class Stack = std::stack,
         class C = std::deque<T>
         >   
class Tower : protected Stack<T,C>
{   
    public:
        Tower() : Stack<T,C>(N)
        {   
        }   
};  


int main(int argc, char **argv)
{   
    Tower<5UL, int> tower1();
    Tower<5UL, int, std::queue> tower2();
    Tower<5UL, int, std::stack, std::deque<int> > tower3();
}   
于 2012-04-08T12:34:10.673 回答