私はここで何をしたいのか正確に説明するのは難しいですが、私は基本クラスとこの基本クラスを継承する2つのクラスを持っています。それを継承する両方のクラスには、独自のメンバーがあります。私はメソッドに両方を渡すことができるようにしたい、そして、そのメソッドがそれを検出して、それらのユニークなメンバーにアクセスするようにしたい。私はそれを継承する2つのクラスだけがあると仮定することはできませんので、私はより一般的な解決策の何かを探しています。メソッドにクラスを渡す方法とベースクラスから継承を検出する方法は?
#include <iostream>
class Base {
public:
int _type;
Base() { }
};
class First : public Base {
public:
int _first_only;
First() { }
};
class Second : public Base {
public:
int _second_only;
Second() { }
};
void test (Base b) {
std::cout << "Type: " << b._type << std::endl;
if(b._type==1) {
std::cout << "First\n";
// Want to be able to do this
std::cout << "Val: " << (First)b._first_only << std::endl;
} else if(b._type==2) {
std::cout << "Second\n";
// And this
std::cout << "Val: " << (Second)b._second_only << std::endl;
}
}
int main() {
First f;
f._first_only=1;
f._type=1;
Second s;
s._type=2;
s._second_only=2;
test(f);
test(s);
}