2012-10-21 80 views
0

我有这个代码使用模板父类A,它有一个模板子类CA需要一个类型(T)和C在其模板参数中采用该类型的对象(T t)。我想要做的是,在类B的继承中,给出C其模板参数,创建一个b对象,并调用C.h成员函数。但我发现了以下错误:当我实例化一个对象B如何通过继承将模板参数传递给模板化的子类?

prog.cpp:10:44: error: too many template-parameter-lists
prog.cpp: In function 'int main()' :
prog.cpp:14:5: error: 'B' was not declared in this scope
prog.cpp:14:7: error: expected ';' before 'b'

template <typename T> struct A { 
    protected: 
     template <T> struct C { 
      T h(T t) { return t * t; } 
     }; 
}; 

template <typename T = int> template <T t = 5> struct B : public A<T>::C<t> {}; 

int main() { 

    B b; 
    b.h(); 

} 

错误被调用。我试过改变了很多东西,但它没有帮助这种情况。例如,我改变了:

template <typename T = int> template <T t = 5> struct B... 

template <typename T = int> struct B... 

,改变

: public A<T>::C<t> {}; 

: public A<T>::C<T t = 5> {}; 

但我收到更加错误:

prog.cpp:10:53: error: non-template 'C' used as template
prog.cpp:10:53: note: use 'A<T>::template C' to indicate that it is a template
prog.cpp:10:66: error: expected '{' before ';' token
prog.cpp: In function 'int main() :
prog.cpp:14:7: error: missing template arguments before 'b'
prog.cpp:14:7: error: expected ';' before 'b'

我也很好奇第一组错误,我得到了B was not declared in this scope。它怎么会不是?这是我定义B的方式吗?我可能做错了什么?

+0

如何从一个基类,因为它是受保护的不可见派生? – Nobody

+0

@无论是否受到保护,都无法获得相同的错误。 – 0x499602D2

+0

这只是一个不能解决问题但显示另一个问题的边节点。另外我不明白你为什么模板C,因为你不使用模板参数。 – Nobody

回答

2

你必须使2只修改了代码:

// First you don't need and should not use 2 templates 
template <typename T = int, T t = 5> struct B 
    // C++ doesn't know that A<T>::C is a template so you should say it here 
    : public A<T>::template C<t> {}; 
+0

'B b' =>'错误:在'b''之前缺少模板参数 – 0x499602D2

+1

@David:即使所有模板参数都由默认值设置,您也必须指定角度大括号。写'B <> b;'。 – Nobody

+0

现在我收到了一些不同的错误 - http://ideone.com/gQ0pgV – 0x499602D2