私はC++を学んでいます。私は基底クラスBase
とその派生クラスDerived
を持っています。そして彼らはpush_back
をstd::vector<Base*> vec
に入れています。 vec[0] == &Base
とvec[1] == &Derived
と仮定すると、仮想機能なしでvec[0]
とvec[1]
の機能を切り替えることができます。コードはこの質問の終わりです。仮想関数なしでそれを行うより良い方法はありますか?純粋なデータクラスが必要なので、非メンバ関数を追加してデータクラスのコードを変更しないようにしたい。どうもありがとうございました。あなたはそれが「基本」を必要とし、適切として「TYPE_」、または「int型(無効)」の代わり残念ながら、これはおそらく、あなたの質問に答えていないバーチャル機能なしで機能を切り替えるより良い方法はありますか?
void SwitchFunction(Base* ptr)
{
auto&& type = typeid(*ptr);
if (type == typeid(Base))
Function(dynamic_cast<Base*>(ptr));
else if (type == typeid(Derived))
Function(dynamic_cast<Derived*>(ptr));
else std::cout << "invalid type(=" << type.name() << ")" << std::endl;
}
「の型ID」を使用する必要はありません
class TypeInterface {
public:
virtual int type(void) = 0;
virtual ~TypeInterface() {}
};
class Base : public TypeInterface {
public:
static constexpr int type_ = 1;
virtual int type(void) {
return type_;
}
virtual ~Base() {}
};
class Derived : public Base {
public:
static constexpr int type_ = 10;
virtual int type(void) {
return type_;
}
virtual ~Derived() {};
};
void Function(Base* ptr) {
std::cout << "function for Base" << std::endl;
}
void Function(Derived* ptr) {
std::cout << "function for Derived" << std::endl;
}
void SwitchFunction(int type, void* ptr) {
switch (type) {
case 1: {
Base* original_type_ptr = static_cast<Base*>(ptr);
Function(original_type_ptr);
break;
}
case 10: {
Derived* original_type_ptr = static_cast<Derived*>(ptr);
Function(original_type_ptr);
break;
}
default:
std::cout << "invalid type(=" << type << ")" << std::endl;
}
}
void test_function_selecter(void) {
Base b;
Derived d;
std::vector<Base*> vec;
vec.push_back(&b);
vec.push_back(&d);
for (auto e: vec) {
SwitchFunction(e->type(), e);
}
}
コードには未定義の動作があります。それらはいくつかの厄介なキャストです。理想的には、C++を学んでいるときにポインタやキャストを使用しないでください。 –
関数を変数として保存するのはどうですか?すべてのインスタンスで使用されている場合は静的にすることができます。 std :: function myFunc = [](void){//何か} –
Striker
ありがとう、Kerrek SB。私はあなたの懸念事項を見つけようとしました。タイプとボイドの組み合わせが間違っているかもしれないことを恐れるかもしれないと思います。私の場合、SwitchFunction(e-> type()、e)は固定形式です。だから私は間違った組み合わせを選ぶことを避けることができると思う – mora