【发布时间】:2015-03-28 01:18:37
【问题描述】:
我有一个模板类A<T>,其中包含一个静态方法foo(),它返回一个A<T> *。我有一个子类B,它专门针对A<int>。
为避免代码重复,我希望 B 利用 A 的静态 foo() 方法。但是,下面会出现编译错误:error: cannot initialize return object of type 'B *' with an rvalue of type 'A<int> *') 但是B * 正好是A<int> *,不是吗?
有没有办法让B使用A的foo()方法?
template <typename T>
class A {
public:
static A *foo() {
// imagine complex code here
return new A<T>();
}
};
// B is a typed specialization of A
class B : public A<int> {
public:
static B *foo() {
return A<int>::foo(); // doesn't compile
}
};
int main() {
B *b = B::foo();
(void)b; // suppress unused variable warning
}
【问题讨论】:
-
I'd like B to take advantage of A's static foo() method,A::foo()是公开的,为什么要在B中复制它? -
因为我省略了细节以保持示例简单:
B::foo()对A::foo()返回的对象做了一些额外的事情。 -
" 但是 B * 正是 A
*,不是吗?" 好吧,不!一点也不。B不是A的特化。A<int>是B的特化。B是一个继承自A<int>的类。这是一种独特的类型。
标签: c++ templates c++11 static-methods