这是我想要实现的简单代码结构:
#include <memory>
#include <vector>
#include <iostream>
#include <cassert>
struct QObject { virtual void sayHi() const = 0; };
struct DerivedQObject1 : public QObject { void sayHi() const override { std::cout << "1\n"; } };
struct DerivedQObject2 : public QObject { void sayHi() const override { std::cout << "2\n"; } };
class BaseClass {
public:
template <class... Types>
void foo(std::shared_ptr<Types>... args)
{
std::vector<std::shared_ptr<QObject>> vector;
pushBack(vector, args...);
assert(!empty(vector));
doFoo(vector);
}
private:
virtual void doFoo(std::vector<std::shared_ptr<QObject>> const& args) = 0;
template<typename LastType>
static void pushBack(std::vector<std::shared_ptr<QObject>>& vector, LastType arg)
{
vector.push_back(arg);
};
template<typename FirstType, typename ...OtherTypes>
static void pushBack(std::vector<std::shared_ptr<QObject>>& vector, FirstType const& firstArg, OtherTypes... otherArgs)
{
vector.push_back(firstArg);
pushBack(vector, otherArgs...);
};
};
class ChildClassA : public BaseClass {
private:
void doFoo(std::vector<std::shared_ptr<QObject>> const& args) override;
};
void ChildClassA::doFoo(std::vector<std::shared_ptr<QObject>> const& args) {
for (auto const& arg : args) {
arg->sayHi();
}
}
int main() {
ChildClassA child;
auto obj1 = std::make_shared<DerivedQObject1>();
auto obj2 = std::make_shared<DerivedQObject2>();
child.foo(obj1, obj2);
}
我想通过使用方法&#39; getGenericXOfA&#39;来到我的C班。返回在类A的泛型参数中使用的类型 甚至可以在Java上使用它吗?我想做那样的事情:
public class B {}
public class A<X extends B> {
X x;
public A(X x) {this.x = x;}
public X getX() {return x;}
}
public class C<A> {
public A getA() {return null;}
public A<T> T getGenericXOfA() {return getA().getX();}
}
或者那样?:
public class C<A<X>> {
public A getA() {return null;}
public X getGenericXOfA() {return getA().getX();}
}
答案 0 :(得分:1)
当您需要A
扩展X
时,您使用了B
的原始类型:
class C<X extends B> {
public A<X> getA() { ... }
public X getGenericXOfA() {
return getA().getX();
}
}
实际上,您正在使用通用参数的名称。它们并不重要,也不能参考现有的课程。
如果你想要像其他类一样拥有相同的泛型类型,你应该重复相同的模板。
答案 1 :(得分:1)
你可以这样做:
public class C<X extends B, Y extends A<X>> {
public Y getA() {return ... }
}