首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

<<C++ Template>>书的源代码编译不过,为什么?解决方案

2012-06-06 
C++ Template书的源代码编译不过,为什么?这本书的随书源代码,我在VC10下面试验了一下,发现竟然编译不

<<C++ Template>>书的源代码编译不过,为什么?
这本书的随书源代码,我在VC10下面试验了一下,发现竟然编译不过:

C/C++ code
#include<deque>template <typename T,          template <typename ELEM> class CONT = std::deque >//编译器报错!!!!!!!class Stack {  private:    CONT<T> elems;         // elements  public:    void push(T const&);   // push element    void pop();            // pop element    T top() const;         // return top element    bool empty() const {   // return whether the stack is empty        return elems.empty();    }};template <typename T, template <typename> class CONT>void Stack<T,CONT>::push (T const& elem){    elems.push_back(elem);    // append copy of passed elem}template<typename T, template <typename> class CONT>void Stack<T,CONT>::pop (){    if (elems.empty()) {        throw std::out_of_range("Stack<>::pop(): empty stack");    }    elems.pop_back();         // remove last element}template <typename T, template <typename> class CONT>T Stack<T,CONT>::top () const{    if (elems.empty()) {        throw std::out_of_range("Stack<>::top(): empty stack");    }    return elems.back();      // return copy of last element}int _tmain(int argc, _TCHAR* argv[]){    return 0;}

VC提示说: error C3201: the template parameter list for class template 'std::deque' does not match the template parameter list for template parameter 'CONT'

我想问,这里的模板写法:
template <typename ELEM> class CONT = std::deque
是否符合C++规范? 为什么要用到嵌套的template声明,<typename ELEM>根本就没有用到啊


[解决办法]
读书还得再认真一点,下面是摘抄 c++-templates 的原话,就在主楼例子程序下面不远。

If you try to use the new version of Stack , you get an error message saying that the default value std::deque is not compatible with the template template parameter CONT. The problem is that a template template argument must be a template with parameters that exactly match the parameters of the template template parameter it substitutes. Default template arguments of template template arguments are not considered, so that a match cannot be achieved by leaving out arguments that have default values.

The problem in this example is that the std::deque template of the standard library has more than one parameter: The second parameter (which describes a so-called allocator) has a default value, but this is not considered when matching std::deque to the CONT parameter.

再往下该书给出了一个能编译的程序。
[解决办法]
http://topic.csdn.net/u/20120603/07/53a28ade-c1c1-4a02-9576-4cca490d041c.html

热点排行