c++ - 在没有虚函数的情况下,有没有更好的方法来切换函数?

标签 c++

我正在学习 C++。我有一个基类,Base ,及其派生类,Derived .他们是push_back进入std::vector<Base*> vec .假设 vec[0] == &Basevec[1] == &Derived , 我可以为 vec[0] 切换功能和 vec[1]没有虚函数。代码在这个问题的最后。没有虚函数有更好的方法吗?我想要纯数据类,我想添加非成员函数来修改它们以避免修改数据类的代码。非常感谢。

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);
    }

}

最佳答案

你不需要 'type_' 或 'int type(void)' 而是使用 'typeid'

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;
}

不幸的是,这可能无法正确回答您的问题,因为它要求“Base”具有虚函数(例如析构函数,只要您的类型涉及层次结构,通常建议将其设为虚函数)

关于c++ - 在没有虚函数的情况下,有没有更好的方法来切换函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36917304/

相关文章:

c++ - 如何在 GCC 5 中处理双 ABI?

c++ - Opencv如何使用MatIterator迭代具有浮点RGB值的彩色图像?

c++ - 如何将插入值从 istringstream 保存到 vector ?

c++ - fatal error : GL/gl. h: 没有那个文件或目录

c++ - 标准复制问题

C++ VS2013 : overwriting default constructor not working

c++ - 谷歌测试 : code coverage

c++ - OSX 磁盘仲裁链接器错误

c++ - 对 `typeinfo for class' 的 undefined reference 和对 `vtable for class' 的 undefined reference

c++ - 使用 Directx 9 的屏幕空间反射