c++ - 在派生类中实现虚函数时避免dynamic_cast

标签 c++ inheritance rtti dynamic-cast

这是一些示例代码,解释了我要实现的目标。

基本上,我有一个算法依赖于类中可用的一些基本操作。我已经在纯抽象基类中定义了这些操作。我想将该算法应用于各种对象,这些对象通过为特定对象派生类来提供这些操作。

但是,就这些操作而言,不同的派生对象彼此不兼容。我的问题是我是否可以避免使用 RTTI 来确保例如 bool derived2::identical(const base* other2)、断言(或其他退出机制)其中 other2 不是 derived2 类型。

一种替代方法是在特定派生对象上对函数算法进行模板化,但这意味着它的实现必须存在于头文件中,我不想这样做,因为 1) 更改算法代码以进行测试目的可能导致重新编译大部分代码 2) 算法的实现将在 header 中公开,而不是很好地存在于对最终用户隐藏的源文件中。

头文件

#include <list>

class base
{
public:
 virtual float difference(const base*) const = 0;
 virtual bool identical(const base*) const = 0; 
};


class derived1 : public base
{
 public:
 float difference(const base* other1) const
 {
  // other1 has to be of type derived1
            if(typeid(other1) == typeid(this))
            {
                    // process ...
            }
            else
            {
                    assert(0);
            }
  return 1;
 }

 bool identical(const base* other1) const
 {
  // other1 has to be of type derived1
            if(typeid(other1) == typeid(this))
            {
                    // compare...
            }
            else
            {
                    assert(0);
            }
  return true;
 }
};


class derived2 : public base
{
 public:
        float difference(const base* other2) const
        { 
             // process ...
  // other2 has to be of type derived2
            return 2;
        }

 bool identical(const base* other2) const
        {
                // do comparison
  // derived1 and derived2 cannot be compared
                return true;
        }
};

// Declaration
int algorithm(std::list<base*>& members);

算法源文件的实现

#include "header_file_containing_base"
int algorithm(std::list<base*>& members)
{
 // This function only relies on the interface defined in base
 // process members;

 return 1;
}

主程序

int main()
{
  // Create lists of derived1 and derived2
  // Run algorithm on these lists
}

最佳答案

你可以使用双重调度(http://en.wikipedia.org/wiki/Double_dispatch)

关于c++ - 在派生类中实现虚函数时避免dynamic_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3200964/

相关文章:

c++ - 正确使用 'extern' 关键字

c++ - 覆盖 C++ 虚方法

python - 在 Python 中从父类调用方法

c++ - 如何从 type_info 获取模板参数的类型

c++ - 忙等待现代处理器的优缺点

c++ - 定义类似关键字的宏只是为了提高代码的可读性

c++ - 数据的 mmap 和页面对齐 - 这会提高性能吗?

c++ - 如何在 C++ 中的基类和派生类之间共享公共(public)默认参数值?

Delphi:在运行时查找从给定基类派生的类?

delphi - 如何检查后代类是否覆盖所有虚拟方法?