2012-04-07 129 views
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

'template<class> class Stack', got 'template<class _Tp, class _Sequence> class std::stack'显示问题。

这里是std::stack看起来像

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

正如你可以看到有一个第二个参数。

添加:

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

应该让编译。

4

std::stack有多个模板参数。因此,它不能用于你的情况。您可以使用模板类型定义在C++ 11中解决此问题。

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; 
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(); 
}