-
Notifications
You must be signed in to change notification settings - Fork 49
Array Generics
brett hartshorn edited this page Jan 22, 2015
·
2 revisions
C++ supports looping over an array of objects, where each item in the array may be a different subclass, as long as they all share a common base class, and the array is typed as the base class. This is not a problem until you want to call a method that is only defined on one of the subclasses. To workaround this problem you can use if isinstance(item,MyClass)
inside the loop to catch any items of that class, and use data members and methods unique to that subclass inside the if-block.
https://github.com/rusthon/Rusthon/blob/master/examples/array_generics.md
class A:
def __init__(self, x:int):
self.x = x
def method1(self) -> int:
return self.x
class B(A):
def method1(self) ->int:
return self.x * 2
def method2(self, y:int):
print( self.x + y )
class C(A):
def method1(self) ->int:
return self.x + 200
def say_hi(self):
print('hi from C')
def main():
a = A( 1 )
b = B( 200 )
c = C( 3000 )
arr = []A( a,b,c )
for item in arr:
print(item.method1())
if isinstance(item, B):
item.method2( 20 )
if isinstance(item, C):
item.say_hi()
c++ output
class A {
public:
std::string __class__;
int x;
void __init__(int x);
int method1();
A() {__class__ = std::string("A");}
};
void A::__init__(int x) {
this->x = x;
}
int A::method1() {
return this->x;
}
class B: public A {
public:
int method1();
void method2(int y);
B() {__class__ = std::string("B");}
};
int B::method1() {
return (this->x * 2);
}
void B::method2(int y) {
std::cout << (this->x + y) << std::endl;
}
class C: public A {
public:
int method1();
void say_hi();
C() {__class__ = std::string("C");}
};
int C::method1() {
return (this->x + 200);
}
void C::say_hi() {
std::cout << std::string("hi from C") << std::endl;
}
int main() {
A _ref_a = A{};_ref_a.__init__(1); std::shared_ptr<A> a = std::make_shared<A>(_ref_a);
B _ref_b = B{};_ref_b.__init__(200); std::shared_ptr<B> b = std::make_shared<B>(_ref_b);
C _ref_c = C{};_ref_c.__init__(3000); std::shared_ptr<C> c = std::make_shared<C>(_ref_c);
std::vector<std::shared_ptr<A>> _ref_arr = {a,b,c};std::shared_ptr<std::vector<std::shared_ptr<A>>>
arr = std::make_shared<std::vector<std::shared_ptr<A>>>(_ref_arr);
for (auto &item: _ref_arr) {
std::cout << item->method1() << std::endl;
if (item->__class__==std::string("B")) {
auto _cast_item = std::static_pointer_cast<B>(item);
_cast_item->method2(20);
}
if (item->__class__==std::string("C")) {
auto _cast_item = std::static_pointer_cast<C>(item);
_cast_item->say_hi();
}
}
return 0;
}